Title: Files and Streams
1Files and Streams
2Outline
IntroductionData HierarchyFiles and
StreamsClasses File and DirectoryCreating a
Sequential-Access File
3 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.
4Â Â 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)
5Â Â 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.
6Â Â Data Hierarchy
Fig. 17.1 Data hierarchy.
7Â Â 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.
8Â Â 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
9Â Â Classes File and Directory
10Â Â 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 ' 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 - 30 fileName txtInput.Text
12- 37
- 54
- 55 ' determine whether fileName is a
directory - 56 ElseIf Directory.Exists(fileName)
Then - 57
- 58 Dim directoryList As String() '
array for directories - Dim i As Integer
- 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
13- 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 " _
14(No Transcript)
15Creating 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.
16Creating 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.
17Creating 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.
18Creating 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.
19Creating 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.
20Creating 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.
21Creating 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.
22Creating 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.
23StreamWriter 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
-
24StreamWriter Class
- The default location where the files we create
are saved is the bin directory of the Windows
Application with which we are working.
25StreamReader
- 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() gt -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
26Example Working with sequential access file
27(No Transcript)
28(No Transcript)
29(No Transcript)
30(No Transcript)
31(No Transcript)
32(No Transcript)
33(No Transcript)
34(No Transcript)
35Demo