Download presentation
Presentation is loading. Please wait.
1
18 Files and Streams
2
Consciousness … does not appear to itself chopped up in bits.
… A “river” or a “stream” are the metaphors by which it is most naturally described. William James I read part of it all the way through. Samuel Goldwyn I can only assume that a “Do Not File” document is filed in a “Do Not File” file. Senator Frank Church Senate Intelligence Subcommittee Hearing, 1975
3
OBJECTIVES In this chapter you will learn:
To create, read, write and update files. The .NET framework streams class hierarchy. To use classes File and Directory to obtain information about files and directories on your computer. To become familiar with sequential-access file processing. To use classes FileStream, StreamReader and StreamWriter to read text from and write text to files. To use classes FileStream and BinaryFormatter to read objects from and write objects to files.
4
18.1 Introduction 18.2 Data Hierarchy 18.3 Files and Streams 18.4 Classes File and Directory 18.5 Creating a Sequential-Access Text File 18.6 Reading Data from a Sequential-Access Text File 18.7 Case Study: A Credit-Inquiry Program 18.8 Serialization 18.9 Creating a Sequential-Access File Using Object Serialization 18.10 Reading and Deserializing Data from a Sequential-Access Text File 18.11 Wrap-Up
5
18.1 Introduction Persistent Data
Data maintained in files Create, upload and process data files in Visual Basic Overview of data hierarchy Overview of FCL’s file-processing classes
6
18.2 Data Hierarchy Data Hierarchy
All data in computers are combinations of 0s and 1s The smallest data item is called a bit (Contains 0 or 1) Bytes are composed of eight bits Visual Basic uses the Unicode® character set in which characters are composed of 2 bytes Characters are composed of bits A field is a group of characters A record/file is composed of several related fields A group of related files often are stored in a database A collection of programs designed to create and manage databases is called a database management system (DBMS)
7
Fig | Data hierarchy.
8
18.3 Files and Streams Files and Streams
Visual Basic views each file as a sequential stream of bytes Each file ends either with: An end-of-file marker Specific byte number Recorded in a system-maintained administrative data structure An object is created and a stream is associated with the object when a file is opened The runtime environment creates three stream objects: Console.In (Refers to the standard input stream object) Enables a program to input data from the keyboard Console.Out (Refers to the standard output stream object) Enables a program to output data to the screen Console.Error (Refers to the standard error stream object) Enables a program to output error messages to the screen
9
Fig. 18.2 | Visual Basic’s view of an n-byte file.
10
18.3 Files and Streams (Cont.)
There are many file-processing classes in the FCL Class StreamReader For text input from a file Inherits from abstract class TextReader Class StreamWriter For text output to a file Inherits from abstract class TextWriter Class FileStream For both input from and output to a file Can be used to write data to and read data from files Inherits from abstract class Stream Class MemoryStream Enables the transfer of data directly to and from memory Class BufferedStream Uses buffering to transfer data to or from a stream Properties of Console.In and Console.Out are of type TextReader and TextWriter, respectively
11
18.3 Files and Streams (Cont.)
Buffering An I/O performance-enhancement technique Each output operation is directed to a buffer Aka region in memory Output is performed more efficiently Large physical output operation each time the buffer fills Less overhead Used to speed input operations Reading more data than is required into a buffer Subsequent reads get data from memory rather than external device
12
18.4 Classes File and Directory
Enable programs to manipulate files and directories on disk Class File Determine information about files and can be used to open files for reading or writing Class Directory Provides capabilities for manipulating directories CreateDirectory Method Returns DirectoryInfo object Contain information about a directory
13
Fig. 18.3 | File class Shared methods (partial list). (Part 1 of 2.)
14
Fig. 18.3 | File class Shared methods (partial list). (Part 2 of 2.)
15
Fig. 18.4 | Directory class Shared methods.
16
Checks to see if filename is an existing file
Outline FrmFileTest.vb (1 of 4 ) Checks to see if filename is an existing file
17
Outline Instantiates a StreamReader for reading text from a file
FrmFileTest.vb (2 of 4 ) Checks to see if filename is an existing directory Obtain a String array containing the names of the subdirectories in the specified directory If successful, output results
18
Outline (3 of 4 ) If not, notify user
FrmFileTest.vb (3 of 4 ) If not, notify user Returns a DateTime object representing when the file was created Returns a DateTime object representing when the file was last modified Returns a DateTime object representing when the file was last accessed
19
Outline FrmFileTest.vb (4 of 4 )
20
Outline Returns the current project’s directory (1 of 6 )
FrmFileSearch.vb (1 of 6 ) Create an object of NameValueCollection
21
Determine if txtInput.Text is an existing directory
Outline FrmFileSearch.vb (2 of 6 ) Determine if txtInput.Text is an existing directory
22
Outline (3 of 6 ) Use key string to access corresponding value
FrmFileSearch.vb (3 of 6 ) Use key string to access corresponding value Reset for the next search Matches any sequence of numbers or letters followed by a period and one or more letters
23
Outline Retrieve the names of all subdirectories that belong to the current directory FrmFileSearch.vb (4 of 6 ) Store the names of files in the current directory Eliminate the directory path Return the matches for the regular expression
24
Determine if this is the first occurrence of the filename extension
Outline FrmFileSearch.vb (5 of 6 ) If not, increment the value associated with the extension Delete the file and decrement the corresponding value
25
Notify user of any unauthorized file access
Outline FrmFileSearch.vb (6 of 6 ) Notify user of any unauthorized file access
26
18.5 Creating a Sequential-Access Text File
Visual Basic imposes no structure on files The concept of a “record” does not exist in C# files Must structure files to meet the requirements of your applications Class FileStream Objects can open files to perform text manipulation Class StreamWriter Objects is constructed with a FileStream argument Specifies the file to output text
27
Define enumeration for the textbox’s indices
Outline FrmBankUI.vb (1 of 3 ) Define enumeration for the textbox’s indices Clear textbox
28
Set textboxes to corresponding values
Outline FrmBankUI.vb (2 of 3 ) Set textboxes to corresponding values
29
Return textboxes’ values
Outline FrmBankUI.vb (3 of 3 ) Return textboxes’ values
30
Outline Private instance values representing all the information for a record Record.vb (1 of 3 ) Initializes the Private instance variables’ value
31
Outline Property for Private instance variable accountValue (2 of 3 )
Record.vb (2 of 3 ) Property for Private instance variable firstNameValue Property for Private instance variable lastNameValue
32
Property for Private instance variable balanceValue
Outline Property for Private instance variable balanceValue Record.vb (3 of 3 )
33
Outline Create a StreamWriter object for writing text to a file
FrmCreateFile.vb (1 of 7 ) Create a FileStream object for connecting to a file Prompt user for location to save file Do not notify user that file does not exist
34
Outline Obtain user-selected file
Open the file if the file exists or create the file if it does not exist FrmCreateFile.vb (2 of 7 ) Indicates that the program can perform only write operations with this object Instantiate the StreamWriter object to write text to a file
35
Outline (3 of 7 ) Create a Record object to hold textboxes’ data
FrmCreateFile.vb (3 of 7 ) Create a Record object to hold textboxes’ data Store record information
36
Write record information
Outline Write record information FrmCreateFile.vb (4 of 7 )
37
Release the program’s resources
Outline Release the program’s resources FrmCreateFile.vb (5 of 7 )
38
Outline FrmCreateFile.vb (6 of 7 )
39
Outline FrmCreateFile.vb (7 of 7 )
40
Common Programming Error 18.1
Failure to open a file before attempting to reference it in a program is a logic error.
41
Performance Tip 18.1 Close each file explicitly when the program no longer needs to reference the file. 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.
42
Performance Tip 18.2 Releasing resources explicitly when they are no longer needed makes them immediately available for reuse by other programs, thus improving resource utilization.
43
18.6 Reading Data from a Sequential-Access Text File
StreamReader method ReadLine Reads a line of text from file Returns Nothing is not more text in the file
44
Fig. 18.10 | Sample data for the program in Fig. 18.9.
45
Outline Create a FileStream object for connecting to a file (1 of 6 )
FrmRead SequentialAccess File.vb (1 of 6 ) Create a StreamReader object for reading text from a file Prompt user for a file to read Check to see if user pressed “Cancel”
46
Outline Open file if exist or throw exception
Indicates that the program can perform only read operations with this object FrmRead SequentialAccess File.vb (2 of 6 ) Instantiate the StreamReader object to read text from a file Read line of text from file Separate stream of characters that was read from the file into strings
47
Outline Store results as a Record object (3 of 6 )
FrmRead SequentialAccess File.vb (3 of 6 ) Release the program’s resources
48
Outline FrmRead SequentialAccess File.vb (4 of 6 )
49
Outline FrmRead SequentialAccess File.vb (5 of 6 )
50
Outline FrmRead SequentialAccess File.vb (6 of 6 )
51
Error-Prevention Tip 18.1 Open a file with the FileAccess.Read file-open mode if the contents of the file should not be modified. This prevents unintentional modification of the contents.
52
18.7 Case Study: A Credit-Inquiry Program
Programs normally start from the beginning of the file to retrieve data sequentially from a file Sometimes it is necessary to process a file sequentially several times FileStream object Can reposition its file-position pointer to any position in the file Pointer contains the next byte to be read from or written Its file-position pointer is set to byte position 0 when file is opened Method Seek Reset the file-position pointer Specify the number of bytes it should be offset from the file’s beginning, end or current position - The part of the file you want to be offset from is chosen using constants from the SeekOrigin enumeration
53
Outline Create a FileStream object for connecting to a file (1 of 8 )
FrmCreditInquiry .vb (1 of 8 ) Create a StreamReader object for reading text from a file Prompt user for the file to read
54
Outline Open file if exist or throw exception (2 of 8 )
FrmCreditInquiry .vb (2 of 8 ) Indicates that the program can perform only read operations with this object Instantiate the StreamReader object to read text from a file Event handler for three buttons’ Click events
55
Outline Reset file-position point back to the beginning of the file
FrmCreditInquiry .vb (3 of 8 ) Read line of text from file
56
Outline FrmCreditInquiry .vb (4 of 8 ) Separate stream of characters that was read from the file into strings and store results as a Record object
57
Outline FrmCreditInquiry .vb (5 of 8 )
58
Release the program’s resources
Outline FrmCreditInquiry .vb (6 of 8 ) Release the program’s resources
59
Outline FrmCreditInquiry .vb (7 of 8 )
60
Outline FrmCreditInquiry .vb (8 of 8 )
61
18.8 Serialization Object Deserialization Object serialization
A serialized object is as a sequence of bytes that includes the object’s: Data Type The types of data stored in the object Serialization can transmit objects between applications over a network Serialized object can be read from the file Object Deserialization The type information and bytes that represent the object and its data can be used to recreate the object in memory 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 throw a SerializationException Both methods require a Stream object as a parameter So that the BinaryFormatter can access the correct stream
62
18.9 Creating a Sequential-Access File Using Object Serialization
Serializable objects Must include <Serializable()> attribute or implement interface ISerializable Indicates to the CLR that objects of class can be serialized Classes that write to or read from a stream must include this in their declarations Must ensure that every instance variable of the class is also serializable Check class declaration to ensure that the type is serializable for variables of reference types All primitive-type variables and Strings are serializable By default, array objects are serializable If the array contains references to other objects, those objects may or may not be serializable
63
Outline Indicate to the CLR that objects of this class can be serialized Record Serializable.vb (1 of 3 ) Private instance values representing all the information for a record Initializes the Private instance variables’ value
64
Outline Property for Private instance variable accountValue (2 of 3 )
Record Serializable.vb (2 of 3 ) Property for Private instance variable firstNameValue
65
Outline Property for Private instance variable lastNameValue (3 of 3 )
Record Serializable.vb (3 of 3 ) Property for Private instance variable balanceValue
66
Common Programming Error 18.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.
67
Outline Using specialize namespaces for serialization
Create a BinaryFormatter object for writing serialized object FrmCreateFile.vb (1 of 7 ) Create a FileStream object for connecting to a file Prompt user for location to save file Determine if user pressed “Cancel”
68
Notify user of any problems with the appropriate message
Outline Notify user of any problems with the appropriate message FrmCreateFile.vb (2 of 7 ) Open the file if the file exists or create the file if it does not exist Indicates that the program can perform only write operations with this object
69
Outline FrmCreateFile.vb (3 of 7 )
70
Write the RecordSerializable object to the output file
Outline Write the RecordSerializable object to the output file FrmCreateFile.vb (4 of 7 ) Catch SerializationException if an exception is thrown during serialization
71
Outline FrmCreateFile.vb (5 of 7 )
72
Outline FrmCreateFile.vb (6 of 7 )
73
Outline FrmCreateFile.vb (7 of 7 )
74
18.10 Reading and Deserializing Data from a Sequential-Access Text File
BinaryFormatter’s Method Deserialize Reads a serialized object from a stream and reforms the object in memory Returns a reference of type Object Must be cast to the appropriate type to manipulate the object
75
Used to read serialized objects
Outline FrmRead Sequential AccessFile.vb (1 of 6 ) Used to read serialized objects
76
Use method Deserialize to read serialized data
Outline FrmRead Sequential AccessFile.vb (2 of 6 ) Use method Deserialize to read serialized data
77
Outline FrmRead Sequential AccessFile.vb (3 of 6 ) Catch SerializationException if an exception is thrown during serialization
78
Outline FrmRead Sequential AccessFile.vb (4 of 6 )
79
Outline FrmRead Sequential AccessFile.vb (5 of 6 )
80
Outline FrmRead Sequential AccessFile.vb (6 of 6 )
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.