Title: Chapter 17 Files and Streams
1Chapter 17 Files and Streams
2Outline
17.1 Introduction17.2Â Â Data Hierarchy17.3Â Â Fil
es and Streams17.4Â Â Classes File and
Directory17.5Â Â Creating a Sequential-Access
File17.6Â Â Reading Data from a Sequential-Access
File17.7Â Â Random-Access Files17.8Â Â Creating a
Random-Access File17.9Â Â Writing Data Randomly
to a Random-Access File17.10Â Â Reading Data
Sequentially from a Random-Access
File17.11Â Â Case Study A Transaction-Processing
Program
317.1 Introduction
- Variables and arrays
- Only temporary
- Variable goes out of scope
- Program terminates
- Files
- Long term storage
- Persistent data in Secondary Storage Devices
- In this chapter, we explain how to create, update
and process data files in Visual Basic programs. - We consider both sequential-access files and
random-access files.
417.2Â Â Data Hierarchy
- Data Hierarchy
- Bit (Binary Digit)
- Either zero or one.
- All data reduced to combinations of bits for
processing. - Byte
- Eight bits
- Character
- Two bytes
- Character set
- Set of all characters used to program and
represent data on a particular computer (Digits,
letters and special symbols)
517.2Â Â Data Hierarchy
- Field
- Group of characters that convey a meaning.
- For example, a field consisting of uppercase and
lowercase letters can represent a persons name. - Record
- Group of several, related fields.
- In a payroll system, for example, a record for a
particular employee might include the following
fields (Employee ID, Name, Address, Hourly pay
rate). - File
- Group of related records
- Record key
- Identifies record to a particular entity.
- Sequential file
- Records stored in order of record-key.
617.2Â Â Data Hierarchy
Fig. 17.1 Data hierarchy.
717.3Â Â Files and Streams
- To perform file processing in Visual Basic,
namespace System.IO must be referenced. - This namespace includes definitions for stream
classes such as - FileStream we use it to read data to, and write
data from, sequential-access and random-access
files. - StreamReader reads from a text file.
- StreamWriter writes to a text file.
- BinaryReader reads from a binary file.
- BinaryWriter writes to a binary file.
- Files are opened by creating objects of these
stream classes.
817.4Â Â Classes File and Directory
- Directory
- Used to organize files
- The \ separator character
- Used to separate directories and files in a path
- C\VisualBasic\MyFile
- Class File
- Used to manipulate and determine information
about files - Cannot write to or read from files directly.
- Class Directory
- Used to manipulate directories
917.4Â Â Classes File and Directory
1017.4Â Â Classes File and Directory
11- 1 ' Fig 17.5 FileTest.vb
- 2 ' Using classes File and Directory.
- 3
- 4 Imports System.IO
- 5 Imports System.Windows.Forms
- 6
- 7 Public Class FrmFileTest
- 8 Inherits Form
- 19 ' invoked when user presses key
- 20 Protected Sub txtInput_KeyDown(ByVal
sender As Object, _ - 21 ByVal e As System.Windows.Forms.KeyEven
tArgs) Handles _ - 22 txtInput.KeyDown
- 23
- 24 ' determine whether user pressed Enter
key - 25 If e.KeyCode Keys.Enter Then
- 26
- 27 Dim fileName As String ' name of
file or directory - 28
- 29 ' get user-specified file or
directory
12- 35 ' get file's creation date,
modification date, etc. - 36 txtOutput.Text
GetInformation(fileName) - 37
- 38 ' display file contents through
StreamReader - 39 Try
- 40
- 41 ' obtain reader and file
contents - 42 Dim stream As StreamReader
- 43 stream New
StreamReader(fileName) - 44 txtOutput.Text
stream.ReadToEnd() - 45
- 46 ' handle exception if
StreamReader is unavailable - 47 Catch exceptionCatch As
IOException - 48
- 49 ' display error
- 50 MessageBox.Show("FILE ERROR",
"FILE ERROR", _ - 51 MessageBoxButtons.OK,
MessageBoxIcon.Error) - 52
- 53 End Try
13- 60
- 61 ' get directory's creation date,
modification date, etc - 62 txtOutput.Text
GetInformation(fileName) - 63
- 64 ' obtain directory list of
specified directory - 65 directoryList
Directory.GetDirectories(fileName) - 66
- 67 txtOutput.Text vbCrLf
vbCrLf _ - 68 "Directory contents"
vbCrLf - 69
- 70 ' output directoryList contents
- 71 For i 0 To directoryList.Length
- 1 - 72 txtOutput.Text
directoryList(i) vbCrLf - 73 Next
- 74
- 75 ' notify user that neither file nor
directory exists - 76 Else
- 77 MessageBox.Show(txtInput.Text
" does not exist", _ - 78 "FILE ERROR",
MessageBoxButtons.OK, _
14- 86 ' get information on file or directory
- 87 Private Function GetInformation(ByRef
fileName As String) _ - 88 As String
- 89
- 90 Dim information As String
- 91
- 92 ' output that file or directory exists
- 93 information fileName " exists"
vbCrLf vbCrLf - 94
- 95 ' output when file or directory was
created - 96 information "Created " _
- 97 File.GetCreationTime(fileName)
vbCrLf - 98
- 99 ' output when file or directory was
last modified - 100 information "Last modified " _
- 101 File.GetLastWriteTime(fileName)
vbCrLf - 102
- 103 ' output when file or directory was
last accessed - 104 information "Last accessed " _
15Demo
1617.5 Creating a Sequential-Access File
- To support file processing, the .NET Framework
provides the System.IO namespace that contains
many different classes to handle almost any type
of file operation you may need to perform. - The parent class of file processing is
FileStream. With FileStream, you can use a
FileStream object to get a stream ready for
processing. - A stream is an abstraction of a sequence of
bytes, such as a file.
1717.5 Creating a Sequential-Access File
- Using FileStream Class
- The FileStream class gives the user the
capability to read from, write to, open, and
close files on a file system. - This class provides access to standard input and
output files. - As one of the most complete classes of file
processing of the .NET Framework, FileStream is
equipped with all necessary properties and
methods. To use it, you must first declare a
variable of it.
1817.5 Creating a Sequential-Access File
- FileStream class has 9 constructors the one we
will the most is - FileStream(String, FileMode, FileAccess)
- Initializes a new instance of the FileStream
class with the specified path, creation mode,
read/write permission. - We use the members of FileAccess and FileMode
Enumerations with the constructors of this class
to create or open a file.
1917.5 Creating a Sequential-Access File
- FileMode
- The members of the FileMode Enumerator are
- FileMode.Append If the file already exists, the
new data will be added to its end. If the file
doesn't exist, it will be created and the new
data will be added to it - FileMode.Create If the file already exists, it
will be deleted and a new file with the same name
will be created. If the file doesn't exist, then
it will be created - FileMode.CreateNew If the file already exists,
the compiler will throw an error. If the file
doesn't exist, it will be created - FileMode.Open If the file exists, it will be
opened. If the file doesn't exist, an error would
be thrown - FileMode.OpenOrCreate If the file already
exists, it will be opened. If the file doesn't
exist, it will be created - FileMode.Truncate If the file already exists,
its contents will be deleted completely but the
file will be kept, allowing you to write new data
to it. If the file doesn't exist, an error would
be thrown.
2017.5 Creating a Sequential-Access File
- FileAccess
- In order to perform an operation on a file, you
must specify to the operating system how to
proceed. One of the options you have is to
indicate the type of access that will be granted
on the file. This access is specified using the
FileAccess enumerator. - The members of the FileAccess enumerator are
- FileAccess.Write New data can be written to the
file. - FileAccess.Read Existing data can be read from
the file. - FileAccess.ReadWrite Existing data can be read
from the file and new data be written to the
file.
2117.5 Creating a Sequential-Access File
- After a file is opened it's FileStream object can
be passed to a BinaryReader, BinaryWriter,
StreamReader and StreamWriter classes to work
with the data in the file. - StreamReader is useful for reading lines of
information from standard text file and
StreamWriter is useful for writing to standard
text files. - BinaryWriter class is used to write binary data
to a file. The BinaryReader is useful to us for
reading the data from the BinaryFile.
2217.5 Creating a Sequential-Access File
- Stream Writing
- A streaming operation is typically used to
create a stream. Once the stream is ready, you
can write data to it. The writing operation is
performed through various classes such as
StreamWriter, BinaryWriter. - Stream Reading
- As opposed to writing to a stream, you may
want to read existing data from it. The Reading
operation is performed through various classes
such as StreamReader, BinaryReader.
2317.5 Creating a Sequential-Access File
- Stream Closing
- When you use a stream, it requests resources from
the operating system and uses them while the
stream is available. - When you are not using the stream anymore, you
should free the resources and make them available
again to the operating system so that other
services can use them. - This is done by closing the stream. To close a
stream, you can call the Close() method of the
class(es) you were using. - Before calling Close(), call the class' Flush()
method to clear the memory areas that the object
was using when performing its operations.
24StreamWriter Class
- 1. Declare FileStream object and create a text
file named file.txt with access mode of writing - Dim fs As New FileStream("file.txt",
FileMode.Create, FileAccess.Write) - 2. Create a new StreamWriter and pass the
filestream object fs as argument - Dim sw As New StreamWriter(fs)
- 3. Write text to the created file using the
WriteLine or Write methods - sw.WriteLine("This is an example of using
file handling in VB .NET.") - sw.WriteLine("This concept is
interesting.") - 4. Close the file
- sw.Close() 'closing the file
- fs.Close() closing the stream
-
25StreamWriter Class
- The default location where the files we create
are saved is the bin directory of the Windows
Application with which we are working.
26StreamReader
- 1. Declare FileStream object to open the file
named file.txt with access mode of reading - Dim fs As New FileStream("file.txt",
FileMode.Open, FileAccess.Read) - 2. Create a new StreamReader and pass the
filestream object fs as argument - Dim sr As New StreamReader(fs)
- 3. Peek method of StreamReader object tells how
much more data is left in the file - While sr.Peek() -1
- 'displaying text from text file in a
RichTextBox for instance - rtbFile.Text sr.ReadLine()
- End While
- 4. Close the file
- sr.Close() 'closing the file
- fs.Close() closing the stream
2717.6Â Â Reading Data from a Sequential-Access File
- The StreamReader class supports several methods
for reading text files and offers a way of
determining whether you are at the end of the
file - Line-by-line ? using ReadLine method.
- An entire file? using ReadToEnd method.
- One character at a time ? using Read method.
28Example Working with sequential access file
29(No Transcript)
30(No Transcript)
31(No Transcript)
32(No Transcript)
33(No Transcript)
34(No Transcript)
35(No Transcript)
36(No Transcript)
37Demo
3817.6Â Â Reading Data from a Sequential-Access File
- Line-by-line
- We can read each line with a ReadLine method.
- To determine whether we have reached the end of
the file, we call the Peek method of the
StreamReader object. - The Peek method reads the next character in the
file without changing the place that we are
currently reading. If we have reached the end of
the file, Peek returns -1.
3917.6Â Â Reading Data from a Sequential-Access File
- An entire file
- You can also read an entire text file from
the current position to the end of the file by
using the ReadToEnd method. - One character at a time If you need to read the
file a character at a time, you can use the Read
method. This method returns the integer character
value of each character read. Following example
demonstrates how to use the Read method
4017.6Â Â Reading Data from a Sequential-Access File
- Dim intSingleChar as Integer Dim
cSingleChar as String While sr.Peek
-1 Â intSingleChar sr.Read()Â ' Convert the
integer value into a character cSingleChar
Chr(intSingleChar)Â End While
4117.6Â Â Reading Data from a Sequential-Access File
- To retrieve data sequentially from a file,
programs normally start from the beginning of the
file, reading data consecutively until the
desired data are found. - A FileStream object can reposition its
file-position pointer (which contains the byte
number of the next byte to be read from or
written to the file) to any position in the
filewe show this feature when we introduce
random-access file-processing applications. - When a FileStream object is opened, its
file-position pointer is set to zero (i.e., the
beginning of the file)