210 likes | 234 Views
Files and Streams. Ch 17. Payroll Example. Persistent Data. Data maintained in files Hierarchical file system A PC contains one or more disks A disk contains 0 or many folders (directories) A folder contains 0 or many files, and 0 or many subfolders. Data Hierarchy.
E N D
Files and Streams Ch 17
Persistent Data • Data maintained in files • Hierarchical file system • A PC contains one or more disks • A disk contains 0 or many folders (directories) • A folder contains 0 or many files, and 0 or many subfolders
Data Hierarchy • The smallest data item is a bit • Characters are composed of bits • A field is a group of characters • A record is composed of several fields • A file can be used to store several records
Files and Streams • C# views each file as a sequential stream of bytes • When a file is opened, • an object is created and a stream is associated with the object
console Streams • Console.In • Standard input stream object • Enables a program to input data from the keyboard • Console.Out • Standard output stream object • Enables a program to output data to the screen • Console.Error • Standard error stream object • Enables a program to output error messages to the screen
File-processing Classes • Class StreamReader • For text input from a file • Class StreamWriter • For text output to a file • Class FileStream • For both input from and output to a file • Class MemoryStream • Enables the transfer of data directly to and from memory • Class BufferedStream • Uses buffering to transfer data to or from a stream
File Open and Save Dialogs • Help specify a filename and path • OpenFileDialog • If the file should already exist • SaveFileDialog • Specify a filename and path for a new file
Sequential-Access File • Data in file are structured into records • Records are read (or written) one at a time, from the start to the end
Serialization • A serialized object is represented as a sequence of bytes, including the object’s: • Data • Type • The types of data stored in the object • Entire serialized object can be written to and read from a file
Class BinaryFormatter • Enables entire objects to be written to or read from a stream • Method Serialize • Writes an object’s representation to a file • Method Deserialize • Reads this representation from a file and reconstructs the original object • Both methods require a Stream object as a parameter • So that the BinaryFormatter can access the correct stream
Class for Serializable Objects • Must include[Serializable] attribute or implement interface ISerializable • Indicates that objects of class can be serialized • Must ensure every instance variable of the class is also serializable • All simple-type variables and strings are serializable
Serializable Class Example [Serializable] publicclassAddress [Serializable] publicclassPhoneNumber [Serializable] publicabstractclassEmployee [Serializable] publicclassSalariedEmployee : Employee
Serializing Objects using System; using System.Windows.Forms; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; namespace Payroll { publicpartialclassPayrollSystemForm : Form {
privatevoid saveToolStripMenuItem_Click(object sender, EventArgs e) { BinaryFormatter formatter = newBinaryFormatter(); FileStream output = null; DialogResult result; string fileName; // name of file to save data using (SaveFileDialog fileChooser = newSaveFileDialog()) { // allow user to create file fileChooser.CheckFileExists = false; result = fileChooser.ShowDialog(); fileName = fileChooser.FileName; }
if (result == DialogResult.Cancel) return; try { // open file with write access output = newFileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); // save records to file foreach (Employee item in lstEmployees.Items) { formatter.Serialize(output, item); } } // end try // handle exception if there is a problem catch (IOException)
privatevoid openToolStripMenuItem_Click(object sender, EventArgs e) { BinaryFormatter reader = newBinaryFormatter(); FileStream input = null; DialogResult result; string fileName; // name of file using (OpenFileDialog fileChooser = newOpenFileDialog()) { result = fileChooser.ShowDialog(); fileName = fileChooser.FileName; // get file name } if (result == DialogResult.Cancel) return;
try { input = newFileStream(fileName, FileMode.Open, FileAccess.Read); // read records from file lstEmployees.Items.Clear(); Employee employee = (Employee)reader.Deserialize(input); while (employee != null) { lstEmployees.Items.Add(employee); employee = (Employee)reader.Deserialize(input); } } catch
Summary • Persistent data • Data maintained in files • C# views each file as a sequential stream of bytes • Sequential-access file • Records in file read/written from start to end • Serialization • Allows entire serialized objects to be written to and read from streams