1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: File and Stream Tujuan Instruksional Khusus: Mahasiswa dapat.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Object Oriented Programming Files and Streams Dr. Mike Spann
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
Serialization objects created in a program reside in RAM through references object o; heap stack content.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Lecture Roger Sutton CO331 Visual Programming 19: Simple file i/o Exceptions – Error handling 1.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
ASP.NET Programming with C# and SQL Server First Edition
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
Sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Review of C++ Programming Part II Sheng-Fang Huang.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
CIS 270—Application Development II Chapter 14—Files and Streams.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
File I/O 11_file_processing.ppt
 2006 Pearson Education, Inc. All rights reserved Files and Streams.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 Pearson Education, Inc. All rights reserved Files and Streams.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message).
Object Serialization. Sequential-access Text Files Sequential-access files store records In order by the record-key field Java imposes no structure on.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams -- Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
CSC 298 Streams and files.
Chapter 21 – Files and Streams 1 Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
The Memento Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Exception Handling. VB.NET has an inbuilt class that deals with errors. The Class is called Exception. When an exception error is found, an Exception.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Introduction to Classes and Objects
Advanced .NET Programming II 6th Lecture
18 Files and Streams.
Serialization.
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
Files and Streams.
Files and Streams Lect3 CT1411.
Introduction to Classes and Objects
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
Files & Streams.
Object Oriented Programming
Fundaments of Game Design
How to work with files and data streams
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams UTPA – Fall 2012 This set of slides is revised from lecture slides of Prof.
Chapter 15 Files, Streams and Object Serialization
Files and Streams.
Presentation transcript:

1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT

2 OBJECTIVES  To use classes FileStream and BinaryFormatter to read objects from and write objects to files.

Serialization 19.9 Creating a Sequential-Access File Using Object Serialization Reading and Deserializing Data from a Binary File

Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields. C# provides such a mechanism, called object serialization. A serialized object is an object represented as a sequence of bytes that includes the object’s data, its type and the types of data stored in the object. After a serialized object has been written to a file, it can be read from the file and deserialized.

Serialization (Cont.) Class BinaryFormatter enables entire objects to be written to or read from a stream. BinaryFormatter method Serialize writes an object’s representation to a file. BinaryFormatter method Deserialize reads this representation from a file and reconstructs the original object. Both methods throw a SerializationException if an error occurs during serialization or deserialization.

6 Defining the S erializable Class Account Class Account is marked with the [Serializable] attribute, which indicates that Account objects can be serialized. Outline Account.cs [Serializable] public class Account { public string First { get; set; } public string Number { get; set; } public string Last { get; set; } private decimal balance; // instance variable that stores the balance public static int totalAcc = 0; public int CurAcc { get; set; } public Account() { totalAcc++; Balance = M; // set balance using property } // end Account constructor

Creating a Sequential-Access File Using Object Serialization (Cont.) The classes for objects that we wish to serialize must include this attribute in their declarations or must implement interface ISerializable. In a serializable class, you must ensure that every instance variable of the class is also serializable. All simple-type variables and string s are serializable. For variables of reference types, their types must be serializable. By default, array objects are serializable. However, if the array contains references to other objects, those objects may or may not be serializable.

8 Using a Serialization Stream to Create an Output File Now let’s create a sequential-access file with serialization (Fig ). Outline CreateFileForm.cs (1 of 11 ) Create a BinaryFormatter for writing serialized objects. using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; // SerializationException namespace BinFile { public partial class Form1 : Form { List myAccList; int numAcc = 0; int curAcc = 0; // object for serializing Records in binary format private BinaryFormatter formatter = new BinaryFormatter(); private BinaryFormatter reader = new BinaryFormatter(); private FileStream output; // stream for writing to a file private FileStream input; // stream for reading from a file Create the BinaryFormatter that will be used to read objects.

9 Outline try { // open file with write access output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); // write Record to file, fields separated by commas // foreach (var acc in myAccList) // write Record to FileStream ( serialize object ) formatter.Serialize(output, myAccList); output.Close(); }// end try // handle exception if there is a problem opening the file catch (SerializationException) { // notify user if file does not exist MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // end catch Call method Serialize to write the entire list of Account object to the output file.

10 Write to Binary File

11 Binary File

12 Outline Common Programming Error 19.2 It is a logic error to open an existing file for output when the user wishes to preserve the file. The original file’s contents will be lost. Method Serialize takes the FileStream object as the first argument so that the BinaryFormatter can write its second argument to the correct file. Remember that we are now using binary files, which are not human readable.

Reading and Deserializing Data from a Binary File try { // create FileStream to obtain read access to file input = new FileStream( fileName, FileMode.Open, FileAccess.Read); // get next RecordSerializable available in file myAccList = (List )reader.Deserialize(input); Account.totalAcc = myAccList.Count; numAcc = Account.totalAcc; curAcc = 0; PopulateAcc(); input.Close(); // close FileStream if no Records in file }// end try // handle exception if there is a problem opening the file catch (SerializationException) { input.Close(); // close FileStream if no Records in file // notify user if no Records in file MessageBox.Show("No more records in file", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); } // end catch Open the file for input by creating a FileStream object. We use method Deserialize (of the BinaryFormatter ) to read the data.

14 Outline 14 Read from Binary File Deserialize returns a reference of type object. If an error occurs during deserialization, a SerializationException is thrown.

Assignment Implement DeleteAccount( ) to delete the current or selected account. Add telephone number to the class Account and implement method Search( ) to search the account using the phone number.