Presentation is loading. Please wait.

Presentation is loading. Please wait.

 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).

Similar presentations


Presentation on theme: " 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)."— Presentation transcript:

1  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). Slides added by L.Lilien are © 2006-2010 Leszek T. Lilien. Permision to use for non- commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

2  2009 Pearson Education, Inc. All rights reserved. 2 19.1 Introduction 19.2 Data Hierarchy 19.3 Files and Streams 19.4 ** SKIP ** Classes File and Directory 19.5 Creating a Sequential-Access Text File 19.6 Reading Data from a Sequential-Access Text File 19.7 ** SKIP** Case Study: Credit Inquiry Program Using LINQ 19.8 Serialization 19.9 Creating a Sequential-Access File Using Object Serialization 19.10 Reading and Deserializing Data from a Binary File

3  2009 Pearson Education, Inc. All rights reserved. 3 19.1 Introduction Variables and arrays are only temporary – Lost during garbage collection or when a program terminates Files used for long term storage – Called persistent data – Stored on secondary storage devices - Can store large amounts of data Much more than in variables or arrays in program memory - Can “carry” data between program executions This chapter deals with: – Sequential-access files Ed. 1 only: Random-access files (not covered in CS 1120) – File processing features – Stream-input and stream-output features Slide modified by L. Lilien

4  2009 Pearson Education, Inc. All rights reserved. 4 19.2 Data Hierarchy (see Fig – next page) – Bit (binary digit) : either ‘1’ or ‘0’ - All data represented as combination of bits - Easy for electronic devices to understand – Byte: eight bits – Character: two bytes in C# (bec. C# uses Unicode ) - Character set: set of all characters used to program and represent data on a particular computer – Field: composition of characters that conveys a meaning – Record: composition of several, related fields - Record key: identifies record (ties it to a given entity) – File: group of related records - Sequential file: typically, records stored in order of record keys (cf. slides 25-27) – Database: a collection of related files (managed by DBMS) - Database management system (DBMS) - collection of programs designed to create and manage databases COMPLEXITY Slide modified by L. Lilien

5  2009 Pearson Education, Inc. All rights reserved. 5 19.2 Data Hierarchy Fig. 19.1 Data hierarchy. RandyRed IrisOrange JudyGreen TomBlue SallyBlack file JudyGreen record Judyfield 01001010 (ASCII for J) byte 1 bit a collection of related files database Slide modified by L. Lilien

6  2009 Pearson Education, Inc. All rights reserved. 6 19.3 Files and Streams File – a sequential stream of bytes – File end determined by: - an end-of-file marker - file length - number of bytes n in the file Recorded in system data structure When file opened in C#: – Creates an object – Associates a stream with that object Slide modified by L. Lilien Fig. 19.2C#’s view of an n-byte file. 012345678n - 1…… end-of -file marker (a.k.a. a sentinel value)

7  2009 Pearson Education, Inc. All rights reserved. 7 19.3 Files and Streams When a console application starts, 3 object of class Stream (see next slide) are created – They facilitate communication: the program a particular file or device – These 3 stream objects are accessed via Console properties: - Property Console.In: returns standard input stream object Enables a program to input from the keyboard - Property Console.Out: returns standard output stream object Enables a program to output to the screen - Property Console.Error: returns standard error stream object Enables a program to output error messages to the screen We have already used Console.In and Console.Out – Console.Read and Console.ReadLine use Console.In implicitly – Console.Write and Console.WriteLine use Console.Out implicitly Slide modified by L. Lilien

8  2009 Pearson Education, Inc. All rights reserved. ++OPTIONAL++ 19.3 Files and Streams Console Class [http://msdn.microsoft.com/en-us/library/system.console.aspx] - public static class Console Console I/O Streams [http://msdn.microsoft.com/en-us/library/system.console.aspx] – When a console application starts, the operating system automatically associates three I/O streams with the console : - the standard input stream — application can read user input from it - the standard output stream — application can write normal data to it - the standard error output stream — application can write error data to it – These streams are presented to your application as the values of the In, Out, and Error properties [of the Console class]InOut Error 8

9  2009 Pearson Education, Inc. All rights reserved. ++OPTIONAL++ Console.In property http://msdn.microsoft.com/en-us/library/system.console.in.aspx http://msdn.microsoft.com/en-us/library/system.console.in.aspx – Gets the standard input stream. – public static TextReader In { get; } // In is of type TextReader – set to the standard input stream by default Console.Out property http://msdn.microsoft.com/en-us/library/system.console.out.aspx http://msdn.microsoft.com/en-us/library/system.console.out.aspx – public static TextWriter Out { get; } // Out is of type TextWriter – set to the standard output stream by default Console.Error Property http://msdn.microsoft.com/en-us/library/system.console.error.aspx http://msdn.microsoft.com/en-us/library/system.console.error.aspx – public static TextWriter Error { get; } // Error is of type TextWriter – set to the standard error stream by default 9

10  2009 Pearson Education, Inc. All rights reserved. 10 19.3 Files and Streams Namespace System.IO namespace is needed for file processing – Includes definitions for stream classes such as: - Class StreamReader - for text input from a file Inherits from abstract class TextReader  Console.In is a Console property of type TextReader - Class StreamWriter - for text output to a file Inherits from abstract class TextWriter  Console.Out and Console.Error are Console properties of type of TextWriter - Class FileStream - for text input/output from/to a file Inherits from abstract class Stream (discussed next) Example: private FileStream output; output = new FileStream( fileName, FileMode.OpenOrCreate, FileAccess.Write ); – Files are opened by creating objects of these stream classes Slide modified by L. Lilien

11  2009 Pearson Education, Inc. All rights reserved. 11 19.3 Files and Streams Abstract class Stream (System.IO.Stream) - allows for representation of streams as bytes – Bytes (representing streams) are stored in files/memory/buffer or – Bytes (representing streams) are retrieved from files/memory/buffer Concrete classes derived from Stream : 1 ) Class FileStream : read/write to/from sequential-access and random-access files - inherits from abstract class Stream 2) Class MemoryStream – transfers data directly to/from memory - Inherits from abstract class Stream - Much faster than data transfer, e.g., to/from disk [cont.] Slide modified by L. Lilien

12  2009 Pearson Education, Inc. All rights reserved. 12 3) Class BufferedStream - uses buffering to transfer data to/from a stream - Inherits from abstract class Stream - Buffering is a technique enhancing performance of I/O operations  I/O = input/output (from/to an output device holding a file) Each output operation is directed to a buffer  Buffer is a region in memory - So transfer (being a memory transfer) is fast!  So we (temporarily) write only into memory instead of writing to (a file on) an output device - (Fast) output to the buffer (in memory) is called logical output - (Slower) output from a buffer to an output device is called physical output Performed when buffer full (or when program terminates) - Q: Why buffering improves performance? - A: Bec. there are many more (fast) logical outputs than (slower) physical outputs **SKIP** 19.3 Files and Streams Slide modified by L. Lilien

13  2009 Pearson Education, Inc. All rights reserved. 13 *** SKIP *** 19.4 Classes File and Directory Slide modified by L. Lilien

14  2009 Pearson Education, Inc. All rights reserved. 14 19.5 Creating a Sequential-Access File In C#, files have no structure – Just a sequence of bytes - No record structure Programmers have to structure files to meet the requirements of applications – Define/create your own record structure within a file - Using text and special characters to “organize” records within files Slide modified by L. Lilien

15  2009 Pearson Education, Inc. All rights reserved. 15 DIGRESSION: Enumeration Enumeration declaration: enum : // modifier: private, public, protected or internal { { Example 1 enum Months// default underlying type is int { JAN, FEB, MAR, APR } By default the first enumerator represented by the value of 0 and the value of each successive enumerator is increased by 1. – In Example 1, the value of JAN is 0, of FEB is 1, …, of APR is 3 Can override default values representing enumerators – Example 2 enum Months { JAN = 10, FEB = 20, MAR = 30, APR = 40 } In Example 2 (in contrast to Example 1), the value of JAN is 10, of FEB is 20, … [cf. Rajesh V. S. - see http://www.c-sharpcorner.com/Language/EnumeratorsInCsharpRVS.asp] Slide added by L. Lilien

16  2009 Pearson Education, Inc. All rights reserved. 16 DIGRESSION: Enumeration – cont. An explicit cast is needed to convert from underlying enum type to another type, e.g., integer type. (This is why the enum types are type-safe in C#.) – Small example int x = Months.JAN; is not a valid C# statement int x = ( int ) Months.JAN ; is a valid C# statement Larger example (incl. converting and printing enum values) using System; enum Months : long // non-default underlying type – 64-bit size { JAN = 10, FEB = 20 } class MyClient { public static void Main() { long x = ( long ) Months.JAN; long y = ( long ) Months.FEB; Console.WriteLine(“JAN value = {0}, FEB value = {1}", x, y); } } Output: JAN value = 10, FEB value = 20 [cf. Rajesh V. S. - see http://www.c-sharpcorner.com/Language/EnumeratorsInCsharpRVS.asp] Slide added by L. Lilien

17  2009 Pearson Education, Inc. All rights reserved. 17 19.5 Creating a Sequential-Access Text File Examples: File processing in a bank-account maintenance application – Class BankUIForm - a reusable windows form for examples (p. 925, ed.3) – Class Record – used for writing/reading records to/from a sequential file (cf. the slides below) – Both classes compiled into a DLL library (“namespace”) named BankLibrary Slide added by L. Lilien

18  2009 Pearson Education, Inc. All rights reserved. 18 19.5 Creating a Sequential-Access Text File Other classes in examples in this and next Sections – Derived from BankUIForm: - public class CreateFileForm : BankUIForm (p.929, ed.3) - public class ReadSequentialAccessFileForm : BankUIForm (p.935, ed.3) Slide added by L. Lilien Figure: GUIs for CreateFileForm and ReadSequentialAccessFileForm add 3 buttons to BankUIForm’s GUI (compare this figure with the figure on the preceding slide)

19  2009 Pearson Education, Inc. All rights reserved. 19 ** SKIP ** 19.5 Creating a Sequential-Access Text File ** SKIP ** Other classes in examples in this and next Sections – Not derived from BankUIForm: (Sec. 19.7, p. 941, ed.3) - public class CreditInquiryForm : Form - Or: - public class CreditInquiryForm : Systems.Windows.Forms.Form Slide added by L. Lilien

20  2009 Pearson Education, Inc. All rights reserved. 20 Outline BankUIForm.cs (1 of 5 ) 19.5.A Class BankUIForm Reusable class BankUIForm inherits from a base-class GUI named Form A partial class (line 8 below) (cf. p. 628-ed.3; also p. 733-ed.3 – more details than covered here) -Means that the class is split among files – not contained in a single file -Reason for splitting: -Part of class created by using Visual Studio’s Toolbox and Properties windows (not by “hand-writing” code) -Part of class manually coded (“hand-written”) -These parts placed in separate files Above‘partial class’ text added by L. Lilien Slide moified by L. Lilien

21  2009 Pearson Education, Inc. All rights reserved. 21 Outline BankUIForm.cs (2 of 5 ) Slide modified by L. Lilien

22  2009 Pearson Education, Inc. All rights reserved. 22 Outline BankUIForm.cs (3 of 5 ) Slide modified by L. Lilien

23  2009 Pearson Education, Inc. All rights reserved. 23 Outline BankUIForm.cs (4 of 5 ) Slide modified by L. Lilien

24  2009 Pearson Education, Inc. All rights reserved. 24 Outline BankUIForm.cs (5 of 5 ) The form generated by BankUIForm.cs Slide modified by L. Lilien To enable reusing BankUIForm: (p. 927, ed.3) -Compile the GUI into BankLibrary DLL (see namespace BankLibrary on prev. slides) -Create the project ‘BankLibrary’ of type Windows Control Library -Later, in any other project using it, add a reference to the project ‘BankLibrary’ -(see ‘using BankLibrary’ in slides below)

25  2009 Pearson Education, Inc. All rights reserved. 25 19.5.B Class Record Class Record -Used in the next few examples -For maintaining the information in each record that is written to or read from a file Also belongs to the BankLibrary DLL -Compile the GUI into ‘BankLibrary’ DLL as before (prev. slide) -So it is located in the same project as BankUIForm Slide modified by L. Lilien

26  2009 Pearson Education, Inc. All rights reserved. 26 RECALL: Auto-implemented property (lines 8-18, next slide) -For example: // An auto-implemented Account property public int Account { get; set; } -It is equivalent to this “manually-implemented” property: // “manually-implemented” Account property public int Account { get { return account; } set { account = value; } } Slide modified by L. Lilien

27  2009 Pearson Education, Inc. All rights reserved. 27 Outline Record.cs (1 of 2 ) Slide modified by L. Lilien

28  2009 Pearson Education, Inc. All rights reserved. 28 Outline Record.cs (2 of 2 ) Slide modified by L. Lilien

29  2009 Pearson Education, Inc. All rights reserved. 29 19.5.C Using a Character Stream to Create an Output File Class CreateFileForm (Fig. 19.9 - below) -Uses instances of class Record -Uses Record for creating a sequential-access file -Class CreateFileForm might be used for accounts-receivable system -Organizes into records data regarding money owed by company’s credit clients -For each client we have: 1) account number, 2) first name, 3) last names, and 4) balance (owed to company) Slide modified by L. Lilien

30  2009 Pearson Education, Inc. All rights reserved. 30 -Class CreateFileForm might be used for accounts-receivable system – cont. -For each client gets: 1) account number, 2) first name, 3) last names, and 4) balance (owed to company) -Data for each client constitutes client’s record -Account number is the key for the record -It is unique for each customer -Key must be unique for each record -This means that records are ordered in the file by the account number (key) -To simplify, we assume that records entered into file in the key (account number ) order -Practical accounts-receivable system would include sorting capability (so records could be entered in any order) Slide modified by L. Lilien

31  2009 Pearson Education, Inc. All rights reserved. 31 DIGRESSION: The using statement (p. 610-ed.3) Slide added by L. Lilien The using statement simplifies releasing resources after their use Do not confuse the using statement with the using directive The general form of a using statement is: using ( ExampleObject exo = new ExampleObject() ) { exo.SomeMethod(); } The above using statement code is equivalent to { ExampleObject exo = new ExampleObject(); try { exo.SomeMethod(); } finally { if ( exo != null ) ( ( IDisposable ) exo ).Dispose(); } // above line releases resource }

32  2009 Pearson Education, Inc. All rights reserved. 32 GUI of CreateFileForm enhanced with buttons Save As, Enter and Exit Slide modified by L. Lilien GUI of BankUIForm Class CreateFileForm enhances GUI of class BankUIForm with buttons Save As, Enter and Exit

33  2009 Pearson Education, Inc. All rights reserved. 33 CreateSequential AccessFile.cs Program Output Slide modified by L. Lilien GUI for the Next Program (Fig. 17.9 [ed.1] - CreateSequentialAccessFile.cs): Creating a sequential-access file = Writing data into a sequential-access file – Example User clicks the “Save As” button in the “Creating a Sequential File” window to start file creation process. File selection dialog window (next slide) appears.

34  2009 Pearson Education, Inc. All rights reserved. 34 CreateSequentialAc cessFile.cs Program Output Slide modified by L. Lilien User creates a file by selecting its drive & directory (by pointing & clicking), and by typing its filename ‘clients.txt’ (into the ‘File name:’ text box) in the displayed file selection dialog window named “Save As”. SaveFileDialog By clicking on directories, select the directory. Then, type file name – it is the created file in the selected directory Type file name

35  2009 Pearson Education, Inc. All rights reserved. 35 After the file location and name are entered, data (records) are entered as follows: User enters data into 4 textboxes, then clicks on ‘Enter’. (For simplicity, user enters data in the ‘Account’ number order; ‘Account’ is the record key) Program stores data in 4 fields of Record 1 (with key: 100) in a file. User enters data into 4 textboxes, then clicks on ‘Enter’. Program stores data in 4 fields of Record 2 (with key: 200) in a file. Slide added by L. Lilien

36  2009 Pearson Education, Inc. All rights reserved. 36 User enters data into 4 textboxes, then clicks on ‘Enter’. Program stores data in 4 fields of Record 3 (with key: 399) in a file. User enters data into 4 textboxes, then clicks on ‘Enter’. Program stores data in 4 fields of Record 4 (with key: 400) in a file. Slide added by L. Lilien

37  2009 Pearson Education, Inc. All rights reserved. 37 Slide added by L. Lilien User enters data into 4 textboxes, then clicks on ‘Enter’. Program stores data in 4 fields of Record 5 (with key: 500) in a file. User clicks on ‘Exit’ to terminate program execution. Program terminates, but all five records remain stored safely.

38  2009 Pearson Education, Inc. All rights reserved. 38 Outline CreateFileForm.cs (1 of 11 ) Slide modified by L. Lilien

39  2009 Pearson Education, Inc. All rights reserved. 39 Outline CreateFileForm.cs (2 of 11 ) Class SaveFileDialog is used for selecting files. SaveFileDialog ‘s method ShowDialog displays the dialog (the window shown below) and returns a DialogResult specifying which button (Save or Cancel) was clicked to close the dialog. Slide modified by L. Lilien SaveFileDialog By clicking on directories, select the directory. Then, type file name – it is the created file in the selected directory Type file name Later compare lines 29-31 to lines 29-30 in Fig. 19.11 (reading existing file). No line corresponding to l.29 there (bec. we are not creating a file there, but use name of an existing file.)

40  2009 Pearson Education, Inc. All rights reserved. 40 Outline CreateFileForm.cs (3 of 11 ) The constant FileMode.OpenOr Create indicates that the FileStream should open the file if it exists or create the file if it does not. WARNING: FileMode.Open­Or Create will overwrite file contents if file exists. To avoid overwriting existing file, use FileMode.Append Slide modified by L. Lilien

41  2009 Pearson Education, Inc. All rights reserved. 41 Outline CreateFileForm.cs (4 of 11 ) An IOException is thrown if there is a problem opening the file or creating the StreamWriter. Slide modified by L. Lilien enterButton_Click is entered after a user clicks “Enter” following writing data into text boxes on the GUI form.

42  2009 Pearson Education, Inc. All rights reserved. 42 Outline CreateFileForm.cs (5 of 11 ) Slide modified by L. Lilien

43  2009 Pearson Education, Inc. All rights reserved. 43 Outline CreateFileForm.cs (6 of 11 ) StreamWriter method WriteLine writes a sequence of characters to a file. Slide modified by L. Lilien xx

44  2009 Pearson Education, Inc. All rights reserved. 44 Outline CreateFileForm.cs (7 of 11 ) Slide modified by L. Lilien

45  2009 Pearson Education, Inc. All rights reserved. 45 Outline CreateFileForm.cs (8 of 11 ) a) BankUI graphical user interface with three additional controls Slide modified by L. Lilien AGAIN: GUI for the Preceding Program (CreateSequentialAccessFile.cs): Creating a sequential-access file = = Writing data into a sequential-access file – Example User clicks the “Save As” button in the “Creating a Sequential File” window to start file creation process. File selection dialog window (next slide) appears.

46  2009 Pearson Education, Inc. All rights reserved. 46 Outline CreateFileForm.cs (9 of 11 ) SaveFileDialog b) Save File dialog Slide modified by L. Lilien The user selects by clicking the appropriate drive, directory, and types filename (‘clients.dat’). Then she clicks Save (or Cancel). By clicking on directories, select the directory. Then, type file name – it is the created file in the selected directory Type file name

47  2009 Pearson Education, Inc. All rights reserved. 47 Outline CreateFileForm.cs (10 of 11 ) c) Account 100, "Nancy Brown", saved with a balance of -25.54 d) Account 200, "Stacey Dunn", saved with a balance of 314.33 Slide modified by L. Lilien

48  2009 Pearson Education, Inc. All rights reserved. 48 Outline CreateFileForm.cs (11 of 11 ) e) Account 399, "Doug Barker", saved with a balance of 0 f) Account 400, "Dave Smith", saved with a balance of 258.34 (g) Account 500, "Sam Stone", saved with a balance of 34.98 (h) Once all accounts are saved, the Exit button closes the application Slide modified by L. Lilien

49  2009 Pearson Education, Inc. All rights reserved. 49 19.5 Creating a Sequential-Access Text File (Cont.) Fig. 19.10 | Sample data for the program of Fig. 19.9. SUMMARIZING, in the sample execution for the program in Fig. 19.9, we entered information for the five accounts shown in Fig. 19.10. Notice that all account number values are unique! (required, since the account number field is the key) 399

50  2009 Pearson Education, Inc. All rights reserved. 50 Outline ** READ LATER ** In this application, the account number is used as the record key—files are created and maintained in account-number order This program assumes that the user enters records in account- number order. Class CreateFileForm ’s GUI enhances GUI of class BankUIForm with buttons Save As, Enter and Exit..

51  2009 Pearson Education, Inc. All rights reserved. 51 19.5 Creating a Sequential-Access Text File (Cont.) ** READ LATER ** Things to pay attention to: – Class SaveFileDialog is used for selecting files – SaveFileDialog method ShowDialog displays the dialog and returns a DialogResult specifying which button was clicked to close the dialog – A SaveFileDialog is a modal dialog —it prevents the user from interacting with any other window in the program until the user closes it. – Method ShowDialog returns a DialogResult specifying which button ( Save or Cancel ) the user clicked to close the dialog. – You can open files for text manipulation by creating objects of class FileStream Slide modified by L. Lilien

52  2009 Pearson Education, Inc. All rights reserved. 52 19.5 Creating a Sequential-Access Text File (Cont.) ** READ LATER** Things to pay attention to: – The constant FileMode.Open­OrCreate indicates that the FileStream should open the file if it exists or create the file if it does not - To preserve the original contents of a file, use FileMode.Append – The constant FileAccess.Write indicates that the program can perform only write operations with the FileStream object - There are two other FileAccess constants: FileAccess.Read for read-only access FileAccess.ReadWrite for both read and write access – An IOException is thrown if there is a problem opening the file or creating the StreamWriter

53  2009 Pearson Education, Inc. All rights reserved. 53 19.5 Creating a Sequential-Access Text File (Cont.) ** READ LATER ** Things to pay attention to: – StreamWriter method WriteLine writes a sequence of characters to a file – The StreamWriter object is constructed with a FileStream argument that specifies the file to which the StreamWriter will output text – Method Close throws an IOException if the file or stream cannot be closed properly

54  2009 Pearson Education, Inc. All rights reserved. 54 ** READ LATER ** 19.5 Creating a Sequential-Access Text File (Cont.) Good Programming Practice 19.1 When opening files, use the FileAccess enumeration to control user access to these files. Good Programming Error 19.1 Failure to open a file before attempting to use it in a program is a logic error.

55  2009 Pearson Education, Inc. All rights reserved. 55 ** READ LATER ** 19.5 Creating a Sequential-Access Text File (Cont.) Performance Tip 19.1 Close each file explicitly when the program no longer needs to reference it. This can reduce resource usage in programs that continue executing long after they finish using a specific file. The practice of explicitly closing files also improves program clarity. Performance Tip 19.2 Releasing resources explicitly when they are no longer needed makes them immediately available for reuse by other programs, thus improving resource utilization.

56  2009 Pearson Education, Inc. All rights reserved. 56 19.6 Reading Data from a Sequential-Access Text File Read data sequentially from a file – Program starts at the beginning of a file & reads data consecutively until the desired data is found - Sometimes necessary to do this several times during execution of a program – File-position pointer: - When a file (a FileStream object) is opened, its file-position pointer is set to ‘0’ (i.e., points to the first byte – the byte at offset ‘0’ – see Slide 5) - Always points to next byte to be read from or written to file Can be repositioned to any point only in a random access file (not covered in CS 1120)

57  2009 Pearson Education, Inc. All rights reserved. 57 19.6 Reading Data from a Sequential-Access File One program can create (or write) a file, and terminate Another program can read the file at any time – In a minute / day / week / … / year / … – As long as the file is not deleted Example: public class ReadSequentialAccessFileForm : BankUIForm – Reads the same file that class CreateFileForm (of Fig. 19.9 [ed.3]) created (wrote) Slide added by L. Lilien

58  2009 Pearson Education, Inc. All rights reserved. 58 GUI for the Next Program (ReadSequentialAccessFile.cs): Reading from a sequential-access file - Example When the program starts, it displays the “Reading a Sequential File” form. User clicks the “Open File” button in the “Reading a Sequential File” window to start file opening process. (Notice that “Next Record” is dimmed) File selection dialog window appears (below). Slide added by L. Lilien User opens file by selecting its drive, directory and name - by pointing & clicking in the displayed file selection dialog window named “Open” (here, clients.txt is selected)

59  2009 Pearson Education, Inc. All rights reserved. 59 After the file is opened, data (records) from the file are read as follows: User clicks on ‘Next Record’. Program displays Record 1, that is, 4 fields of Record 1 from the file. (As you remember, ‘Account’ is the record key and data were stored in the file in the ‘Account’ number order. Thus, the first record displayed is the one with the lowest key: 100.) User clicks on ‘Next Record’. Program displays Record 2 (key: 200), that is, 4 fields of Record 2 from the file. Slide added by L. Lilien

60  2009 Pearson Education, Inc. All rights reserved. 60 User clicks on ‘Next Record’. Program displays Record 3 (key: 399) that is, 4 fields of Record 3 from the file. User clicks on ‘Next Record’. Program displays Record 4 (key: 400), that is, 4 fields of Record 4 from the file. Slide added by L. Lilien

61  2009 Pearson Education, Inc. All rights reserved. 61 User clicks on ‘Next Record’. Program displays Record 5 (key: 500), that is, 4 fields of Record 5 from the file. User clicks on ‘Next Record’. Program shows ‘No more records in file’ since end of file has been reached. Slide added by L. Lilien

62  2009 Pearson Education, Inc. All rights reserved. 62 Outline ReadSequential AccessFileForm. cs (1 of 8 )

63  2009 Pearson Education, Inc. All rights reserved. 63 Outline ReadSequential AccessFileForm.cs (2 of 8 ) Create an OpenFile­ Dialog, and call its ShowDialog method to display the Open dialog. Equal to “OK” if user clicked “Open” button (not “Cancel” button) in the OpenFileDialog window Slide modified by L. Lilien

64  2009 Pearson Education, Inc. All rights reserved. 64 Outline ReadSequential AccessFileForm.cs (3 of 8 ) Create a FileStream object, passing constant FileMode.Open as the second argument to the FileStream constructor. Slide modified by L. Lilien

65  2009 Pearson Education, Inc. All rights reserved. 65 Outline ReadSequential AccessFileForm.cs (4 of 8 ) StreamReader method ReadLine reads the next line from the file. We created record by concatenating values separated by commas. Split separates the fields from a given record. Now, consecutive elements of the inputFields string array store consecutive fields of a customer’s record from the file (i.e., they store: acct no, first name, last name, and balance).

66  2009 Pearson Education, Inc. All rights reserved. 66 Outline ReadSequential AccessFileForm.cs (5 of 8 ) Construct a Record object using the data from the inputFields string array. Display the Record values in the TextBox es.

67  2009 Pearson Education, Inc. All rights reserved. 67 Outline ReadSequential AccessFileForm.cs (6 of 8 ) AGAIN: GUI for the Preceding Program (ReadSequentialAccessFileForm.cs): Read data from a sequential-access file – Example a) User clicks the “Open File” button in the “Reading a Sequential File” window to start reading from a file. File selection dialog window (next slide) appears.

68  2009 Pearson Education, Inc. All rights reserved. 68 Outline ReadSequential AccessFileForm.cs (7 of 8 ) b) OpenFileDialog window c) Reading account 100d) Reading account 200

69  2009 Pearson Education, Inc. All rights reserved. 69 Outline ReadSequential AccessFileForm.cs (8 of 8 ) g) Reading account 500 e) Reading account 399f) Reading account 400 h) User is shown a messagebox when all records have been read

70  2009 Pearson Education, Inc. All rights reserved. 70 ** READ LATER ** 19.6 Reading Data from a Sequential-Access Text File (Cont.) Things to pay attention to: – The behavior and GUI for the Sav e dialog type (used for creating file in previous section) and Open dialog type (used for reading file in this section) are identical, except that Save is replaced by Open – Specify read-only access to a file by passing constant FileAccess.Read as the third argument to the FileStream constructor – StreamReader method ReadLine reads the next line from the file

71  2009 Pearson Education, Inc. All rights reserved. 71 ** READ LATER ** 19.6 Reading Data from a Sequential-Access Text File (Cont.) Error-Prevention Tip 19.1 Open a file with the FileAccess.Read file-open mode if its contents should not be modified. This prevents unintentional modification of the contents.

72  2009 Pearson Education, Inc. All rights reserved. 72 ** OPTIONAL ** 19.7 Case Study: Reading Data from a Sequential-Access Text File NOTE: The slides are based on ed.1 and differ from Section 19.7 in ed.3. To understand this OPTIONAL material, you need to read Sections 19.8 – 19.10 first (to understand Binary Formatter, serialization, & deserialization) RichTextBox : – Provides more functionality than TextBox – Among others, provides: - LoadFile : method to display file contents - Find : method for searching individual strings - Can display multiple lines of text by default TextBox by default displays one line of text only See input/output behavior of the program: next Slides

73  2009 Pearson Education, Inc. All rights reserved. 73 CreditInquiry. cs 1 // Fig. 17.12 [ed.1]: CreditInquiry.cs 2 // Read a file sequentially and display contents based on 3 // account type specified by user (credit, debit or zero balances). 4 5 // C# namespaces 6 using System; 7 using System.Drawing; 8 using System.Collections; 9 using System.ComponentModel; 10 using System.Windows.Forms; 11 using System.Data; 12 using System.IO; 13 using System.Runtime.Serialization.Formatters.Binary; 14 using System.Runtime.Serialization; 15 16 // Deitel namespaces 17 using BankLibrary; // as defined for ed.1 (not ed.3) 18 19 public class CreditInquiryForm : System.Windows.Forms.Form 20 { 21 private System.Windows.Forms.RichTextBox displayTextBox; 22 23 private System.Windows.Forms.Button doneButton; 24 private System.Windows.Forms.Button zeroButton; 25 private System.Windows.Forms.Button debitButton; 26 private System.Windows.Forms.Button creditButton; 27 private System.Windows.Forms.Button openButton; 28 29 private System.ComponentModel.Container components = null; 30 31 // stream through which serializable data are read from file 32 private FileStream input; 33 34 // object for deserializing Record in binary format 35 BinaryFormatter reader = new BinaryFormatter(); ** OPTIONAL **

74  2009 Pearson Education, Inc. All rights reserved. 74 CreditI nquiry. cs 36 37 // name of file that stores credit, debit and zero balances 38 private string fileName; 39 40 [STAThread] 41 static void Main() 42 { 43 Application.Run( new CreditInquiryForm() ); 44 } 45 46 // Visual Studio.NET generated code 47 48 // invoked when user clicks Open File button 49 private void openButton_Click( 50 object sender, System.EventArgs e ) 51 { 52 // create dialog box enabling user to open file 53 OpenFileDialog fileChooser = new OpenFileDialog(); 54 DialogResult result = fileChooser.ShowDialog(); 55 56 // exit event handler if user clicked Cancel 57 if ( result == DialogResult.Cancel ) 58 return; 59 60 // get name from user 61 fileName = fileChooser.FileName; 62 63 // show error if user specified invalid file 64 if ( fileName == "" || fileName == null ) 65 MessageBox.Show( "Invalid File Name", "Error", 66 MessageBoxButtons.OK, MessageBoxIcon.Error ); User clicked open buttonInstantiate OpenFilelDialogShow OpenFileDialog ** OPTIONAL **

75  2009 Pearson Education, Inc. All rights reserved. 75 67 else 68 { 69 // enable all GUI buttons, except for Open file button 70 openButton.Enabled = false; 71 creditButton.Enabled = true; 72 debitButton.Enabled = true; 73 zeroButton.Enabled = true; 74 } 75 76 } // end method openButton_Click 77 78 // invoked when user clicks credit balances, 79 // debit balances or zero balances button 80 private void get_Click( object sender, System.EventArgs e ) 81 { 82 // convert sender explicitly to object of type button 83 Button senderButton = ( Button )sender; 84 85 // get text from clicked Button, which stores account type 86 string accountType = senderButton.Text; 87 88 // read and display file information 89 try 90 { 91 // close file from previous operation 92 if ( input != null ) 93 input.Close(); 94 95 // create FileStream to obtain read access to file 96 input = new FileStream( fileName, FileMode.Open, 97 FileAccess.Read ); 98 99 displayTextBox.Text = "The accounts are:\r\n"; 100 Button click event handler Reference to object that sent eventGet text from clicked button Create (open) read-only FileStream for input ** OPTIONAL **

76  2009 Pearson Education, Inc. All rights reserved. 76 101 // traverse file until end of file 102 while ( true ) 103 { 104 // get next Record available in file 105 Record record = ( Record )reader.Deserialize( input ); 106 107 // store record's last field in balance 108 Double balance = record.Balance; 109 110 // determine whether to display balance 111 if ( ShouldDisplay( balance, accountType ) ) 112 { 113 // display record 114 string output = record.Account + "\t" + 115 record.FirstName + "\t" + record.LastName + 116 new string( ' ', 6 ) + "\t"; 117 118 // display balance with correct monetary format 119 output += String.Format( 120 "{0:F}", balance ) + "\r\n"; 121 122 // copy output to screen 123 displayTextBox.Text += output; 124 } 125 } 126 } 127 128 // handle exception when file cannot be closed 129 catch( IOException ) 130 { 131 MessageBox.Show( "Cannot Close File", "Error", 132 MessageBoxButtons.OK, MessageBoxIcon.Error ); 133 } 134 While loop to read from file Read input from file ** OPTIONAL **

77  2009 Pearson Education, Inc. All rights reserved. 77 135 // handle exception when no more records 136 catch( SerializationException ) 137 { 138 // close FileStream if no Records in file 139 input.Close(); 140 } 141 142 } // end method get_Click 143 144 // determine whether to display given record 145 private bool ShouldDisplay( double balance, string accountType ) 146 { 147 if ( balance > 0 ) 148 { 149 // display credit balances 150 if ( accountType == "Credit Balances" ) 151 return true; 152 } 153 154 else if ( balance < 0 ) 155 { 156 // display debit balances 157 if ( accountType == "Debit Balances" ) 158 return true; 159 } 160 161 else // balance == 0 162 { 163 // display zero balances 164 if ( accountType == "Zero Balances" ) 165 return true; 166 } 167 Method to determine whether to display each record in file No more records exception Close FileStream ** OPTIONAL **

78  2009 Pearson Education, Inc. All rights reserved. 78 168 return false; 169 170 } // end method ShouldDisplay 171 172 // invoked when user clicks Done button 173 private void doneButton_Click( 174 object sender, System.EventArgs e ) 175 { 176 // determine whether file exists 177 if ( input != null ) 178 { 179 // close file 180 try 181 { 182 input.Close(); 183 } 184 185 // handle exception if FileStream does not exist 186 catch( IOException ) 187 { 188 // notify user of error closing file 189 MessageBox.Show( "Cannot close file", "Error", 190 MessageBoxButtons.OK, MessageBoxIcon.Error); 191 } 192 } 193 194 Application.Exit(); 195 196 } // end method doneButton_Click 197 198 } // end class CreditInquiryForm Done button clicked event handler ** OPTIONAL **

79  2009 Pearson Education, Inc. All rights reserved. 79 Program Output ** OPTIONAL **

80  2009 Pearson Education, Inc. All rights reserved. 80 ** OPTIONAL **

81  2009 Pearson Education, Inc. All rights reserved. 81 19.8 Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields C# provides a mechanism that supports reading or writing entire objects — called object serialization A serialized object is represented as a sequence of bytes – This sequence of bytes 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 back into the original object

82  2009 Pearson Education, Inc. All rights reserved. 82 ++READ LATER++ 19.8 Serialization (Cont.) Class BinaryFormatter enables entire objects to be written to or read from a stream – Its method Serialize writes an object’s representation to a file – Its method Deserialize reads this representation from a file and reconstructs the original object – Both Serialize and Deserialize methods can throw a SerializationException - If an error occurs during serialization or deserialization

83  2009 Pearson Education, Inc. All rights reserved. 83 Class BinaryFormatter : converts (serializes or deserializes) original objects from/to the corresponding Stream objects – Method Serialize: Convert an original object into a stream object (that can later be written to a file without losing any of that object’s data) original object --[BinaryFormatter.Serialize]--> Stream object Note an analogy to the ‘ToString’ methods that were used to convert objects to strings. (The ‘ToString’ conversion was not for files – for converting in-memory objects to strings only!). – Method Deserialize: Convert a stream object (read earlier from a file) into the original object Stream object --[BinaryFormatter.Deserialize ]--> original object Slide modified by L. Lilien 19.8 Serialization (Cont.)

84  2009 Pearson Education, Inc. All rights reserved. 84 Serialize/Deserialize methods are used when writing-to/reading-from a binary file The sequence of actions when writing an object to a binary file Step 1: original --[binaryFormatter.Serialize]--> Stream object object Step 2: Stream --[FileStream]--> binary file object The sequence of actions when reading an object from a binary file (reverse of above actions for writing an object to a file) Step 1: binary file --[FileStream]--> Stream object Step 2: Stream --[binaryFormatter.Deserialize]--> original object object Slide added by L. Lilien 19.8 Serialization (Cont.)

85  2009 Pearson Education, Inc. All rights reserved. 85 A)Defining the RecordSerializable Class Class RecordSerializable is marked with the [Serializable] attribute - It indicates that class objects can be serialized Outline Record Serializable.cs (1 of 2 ) 19.9 Creating a Sequential-Access File Using Object Serialization

86  2009 Pearson Education, Inc. All rights reserved. 86 Outline Record Serializable.cs (2 of 2 ) NOTE: The only difference between class Record (Fig.19.8) and class RecordSerializable (above) are two lines (Lines 3 and 7) added to the latter.

87  2009 Pearson Education, Inc. All rights reserved. 87 19.9 Creating a Sequential-Access File Using Object Serialization (Cont.) Class for objects that we wish to serialize must either: – Include the [Serializable] attribute in its declarations or – Implement interface Iserializable ++READ LATER++ 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, you must check their class declaration (and possbly its base class) to ensure that the type is serializable – By default, array objects are serializable - However, if the array contains references to other objects, you must check that those objects are serializable

88  2009 Pearson Education, Inc. All rights reserved. 88 B) Using a Serialization Stream to Create an Output File A sequential-access file with serialization (Fig. 19.14). Outline CreateFileForm.cs (1 of 11 ) Create a BinaryFormatter for writing serialized objects. RECALL: The sequence of actions when writing an object to a binary file Step 1: original --[binaryFormatter.Serialize]--> Stream object object Step 2: Stream --[FileStream]--> binary object file

89  2009 Pearson Education, Inc. All rights reserved. 89 Outline CreateFileForm.cs (2 of 11 ) As before for text files, a user starts by clicking on “Save As” above. Window shown below appears then, so the user can select directory and type in file name.

90  2009 Pearson Education, Inc. All rights reserved. 90 Outline CreateFileForm.cs (3 of 11 )

91  2009 Pearson Education, Inc. All rights reserved. 91 Outline CreateFileForm.cs (4 of 11 )

92  2009 Pearson Education, Inc. All rights reserved. 92 Outline CreateFileForm.cs (5 of 11 )

93  2009 Pearson Education, Inc. All rights reserved. 93 Outline CreateFileForm.cs (6 of 11 ) Call method Serialize to write the RecordSerializable object (record) to the output file. RECALL: The sequence of actions when writing an object to a binary file Step 1: original --[binaryFormatter.Serialize]--> Stream object object Step 2: Stream --[FileStream]--> binary object file

94  2009 Pearson Education, Inc. All rights reserved. 94 Outline CreateFileForm.cs (7 of 11 )

95  2009 Pearson Education, Inc. All rights reserved. 95 Outline CreateFileForm.cs (8 of 11 ) a) a user starts by clicking on the “Save As” button (as before for text files) b) the “Save As” file dialog window (shown below) appears, so the user can select directory and type in file name. SaveFileDialog Files and directories Type in file name

96  2009 Pearson Education, Inc. All rights reserved. 96 Outline CreateFileForm.cs (9 of 11 ) c) Account 100, “Nancy Brown”, saved with a balance of -25.54 d) Account 200, “Stacey Dunn”, saved with a balance of 314.33 f) Account 400, “Dave Smith”, saved with a balance of 258.34 e) Account 399, “Doug Barker”, saved with a balance of 0

97  2009 Pearson Education, Inc. All rights reserved. 97 Outline CreateFileForm.cs (10 of 11 ) g) Account 500, “Sam Stone”, saved with a balance of 34.98 h) Once all accounts are saved, the Exit button closes the application IMPORTANT: Remember that binary files (e.g, created by object serialization) are not human readable In contrast, text files (used before, in Sec. 19.5 – 19.6) are human readable

98  2009 Pearson Education, Inc. All rights reserved. 98 Outline CreateFileForm.c s (11 of 11 ) READ LATER 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.

99  2009 Pearson Education, Inc. All rights reserved. 99 Read and display the contents of the binary file created by the previous program (which serialized & wrote objects into a binary file) Outline ReadSequential AccessFileForm.cs (1 of 8 ) Create the BinaryFormatter that will be used to deserialize read objects. 19.10 Reading and Deserializing Data from a Binary File

100  2009 Pearson Education, Inc. All rights reserved. 100 Outline ReadSequential AccessFileForm.cs (2 of 8 ) As before for text files, a user starts by clicking on “Open File” above. Window shown below appears then, so the user can select directory and file.

101  2009 Pearson Education, Inc. All rights reserved. 101 Outline ReadSequential AccessFileForm.cs (3 of 8 ) Open the file for input by creating a FileStream object.

102  2009 Pearson Education, Inc. All rights reserved. 102 Outline ReadSequential AccessFileForm.cs (4 of 8 ) We use method Deserialize (of the BinaryFormatter ) to read the data.

103  2009 Pearson Education, Inc. All rights reserved. 103 Outline ReadSequential AccessFileForm.cs (5 of 8 )

104  2009 Pearson Education, Inc. All rights reserved. 104 Outline ReadSequential AccessFileForm.cs (6 of 8 ) a) a user starts by clicking on the “Open File” button (as before for text files) b) the “Open” file dialog window (shown below) appears, so the user can select directory and file name.

105  2009 Pearson Education, Inc. All rights reserved. 105 Outline ReadSequential AccessFileForm.cs (7 of 8 ) c) User clicks on “Next Record” to read account 100 e) User clicks on “Next Record” to read account 399 f) User clicks on “Next Record” to read account 400 d) User clicks on “Next Record” to read account 200

106  2009 Pearson Education, Inc. All rights reserved. 106 Outline ReadSequential AccessFileForm.cs (8 of 8 ) g) User clicks on “Next Record” to read account 500 h) User clicks again and is shown a messagebox when all records have been read Things to remember: Deserialize returns a reference of type object If an error occurs during deserialization, a SerializationException is thrown (not “DeserializationException”).

107  2009 Pearson Education, Inc. All rights reserved. 107 IMPORTANT NOTE: There is another type of files: Random-Access Files Edition 1 of this textbook included: 17.7 Random-Access Files 17.8 Creating a Random-Access File 17.9 Writing Data Randomly to a Random-Access File 17.10 Reading Data Sequentially from a Random-Access File 17.11 Case Study: A Transaction-Processing Program

108  2009 Pearson Education, Inc. All rights reserved. 108 The End of Ch.19 (Files & Streams)


Download ppt " 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)."

Similar presentations


Ads by Google