Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.

Similar presentations


Presentation on theme: "Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I."— Presentation transcript:

1 Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I

2 Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File Serialization Using Dialogs File Exception Handling Case Study: A Transaction-Processing Program

3 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 will consider “sequential-access” files. Introduction

4 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) Data Hierarchy

5 Field Group of characters that convey a meaning. For example, a field consisting of uppercase and lowercase letters can represent a person’s 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. Data Hierarchy

6 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. Files and Streams

7 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. Creating a Sequential-Access File

8 FileStream class has 9 constructors the one we will use 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. Creating a Sequential-Access File

9 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. Creating a Sequential-Access File

10 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. Creating a Sequential-Access File

11 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. Creating a Sequential-Access File

12 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. Creating a Sequential-Access File

13 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. Creating a Sequential-Access File

14 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 StreamWriter Class

15 The default location where the files we create are saved is the bin directory of the Windows Application with which we are working. StreamWriter Class

16 StreamReader 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

17 Example – Working with sequential access file

18

19

20

21

22

23

24

25

26

27 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.

28 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.

29 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:

30 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

31 Files using File Dialogues

32

33

34 1 2

35

36 1 2 3

37 Exception Handling VB.NET has an inbuilt class that deals with errors. The Class is called Exception. When an exception error is found, an Exception object is created. The coding structure VB.NET uses to deal with such Exceptions is called the Try … Catch structure. In the coding area for your button, type the word Try. Then hit the return key on your keyboard. VB.NET completes the rest of the structure for you: Try Catch ex As Exception End Try

38 Exception Handling The Try word means “Try to execute this code”. The Catch word means “Catch any errors here”. The ex is a variable, and the type of variable is an Exception object. When you run your program, VB will Try to execute any code in the Try part. If everything goes well, then it skips the Catch part. However, if an error occurs, VB.NET jumps straight to Catch.

39 Exception Handling Dim x As Integer = TextBox1.Text Dim y As Integer = TextBox2.Text Dim z As Integer Try z = x / y MsgBox(z) Catch ex As Exception MsgBox(ex.Message) End Try


Download ppt "Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I."

Similar presentations


Ads by Google