Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.

Slides:



Advertisements
Similar presentations
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Advertisements

Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
Lecture Roger Sutton CO331 Visual Programming 19: Simple file i/o Exceptions – Error handling 1.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Chapter 9 Files I/O: Files, Records and Fields. Basics of File Input and Output Have created both input and outputs from programs. Persistent data: What.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Visual C Sharp – File I/O - 1 Variables and arrays only temporary - lost when a program terminates Files used for long term storage (Data bases considered.
File Handling. Data Files Programs that can only get data from the user interface are limited. –data must be entered each time. –only small amounts of.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
File I/O 11_file_processing.ppt
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
Introduction to Exception Handling and Defensive Programming.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Chapter 10 Sequential Files and Structures. Class 10: Sequential Files Work with different types of sequential files Read sequential files based on the.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
File I/O What We’ll Cover –Visual Basic Techniques for Text Files –.NET Techniques for Text Files What We’ll Not Cover –Binary File I/O –XML File I/O.
Object Oriented Software Development 10. Persistent Storage.
INPUT AND OUTPUT 1. OUTPUT TextBoxes & Labels MsgBox Function/Method MessageBox Class Files (next topic) Printing (later) 2.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter 14: Files and Streams. 2Microsoft Visual C# 2012, Fifth Edition Files and the File and Directory Classes Temporary storage – Usually called computer.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
CSC 298 Streams and files.
File IO.  File Input/Output  StreamWriter  StreamReader  Text Files  Binary Files.
BACS 287 File-Based Programming. BACS 287 Data Hierarchy  Database - Collection of files, relationships, integrity information, etc  Files - All records.
Ajay Tripathi Input Output. Ajay Tripathi Input/output (IO) refers to the operations for reading and writing data to streams and files. In the.NET Framework,
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Chapter 6: Using VB.NET Supplied Classes Visual Basic.NET Programming: From Problem Analysis to Program Design.
VB.Net. Topics Introduction to VB.Net Creating VB.Net Project in VS 2005 Data types and Operators in VB.Net String Functions Conditions (If Else, Select.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 6: Creating Windows–based Applications 1 Microsoft® Visual C# 2008.
Reading & writing to files
Files.
18 Files and Streams.
How to work with files and data streams
Files and Streams.
Exception Handling.
Files and Streams Lect3 CT1411.
Sequential Input and Output using Text Files
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Files & Streams.
Exception Handling.
Files and Streams Lect10 GC201 12/1/2015.
Topics Introduction to File Input and Output
How to work with files and data streams
Introduction to Programming Lecture 6
Files and Streams.
Topics Introduction to File Input and Output
Presentation transcript:

Files and Streams

Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file I/O model Connecting files and streams Learn how to read sequential text files Learn how to write sequential text files Text files = streams of characters perhaps with special characters (often the end of line character) that mark the end of a line.

Data Hierarchy

The Directory Class Common methods of the Directory class  Exists (path designation)  CreateDirectory (path designation)  Delete (path designation) Code that uses some of the Directory methods Dim dir As String = "C:\VB 2005\Files\" If Not Directory.Exists(dir) Then Directory.CreateDirectory(dir) End If

The Directory Class

The File Class Common methods of the File class  Exists (path)  Delete (path)  Copy (source, dest)  Move (source, dest) Code that uses some of the File methods Dim path As String = dir & "Products.txt" If File.Exists(path) Then File.Delete(path) End If

The File Class

Introduction to Files and Streams System.IO classes are used to work with files and streams You can work with two kinds of files – text files (containing only characters) and binary files In this Lecture Set, we discuss text files in detail – we present material on binary files later but will not discuss them in this course

Text vs Binary Files A text file displayed in a text editor A binary file displayed a text editor

Introduction to Processing Textual Data One way to process textual files is from beginning to end using sequential access This type of file is called a sequential file Sequential files can be categorized into roughly three types  Free-form files have no particular format  Fields in a delimited file are separated with a special character called a delimiter  In a fixed-field file, each field occupies the same character positions in every record There are other types of files in addition to sequential files: binary files; direct (random or indexed) access files

Introduction to Processing Textual Data Delimited file Fixed-field file

The Object Framework For files, the object is an instance of a class that provides an abstract view of a file. This view is modeled by a Stream class (StreamReader or StreamWriter classes). The connection – via creation of a streamReader or streamWriter object The stream abstraction (methods and data stores) of a file that you program against (reading and writing an entire file, a line at a time, or a field at a time) The actual, physical file to be manipulated

The Stream-File Connection When you program the manipulation of files, you are really programming “against” the stream abstraction:  FileStream  StreamReader  StreamWriter  BinaryReader  BinaryWriter

Establishing Connections There are several different ways to establish file- stream connections 1. Create a FileStream object Dim path as String = “C:\VB 2005\Files\Products.txt Dim fs as New FileStream(path, FileMode.create, _ FileAccess.Write) 2. Create a StreamReader object 3. Create a StreamWriter object The results of using these techniques are similar – they all result in the creation of (or opening of) a stream (fs) against which all subsequent file operations are written

The FileStream Class The syntax for creating a FileStream object New FileStream(path, FileMode, FileAccess, share]]) Members in the FileMode enumeration  Append – opens a file if it exists and place the write pointer at the end of the file  Create – Creates a new file. If file exists it is overwritten  CreateNew – Creates a new file. If file already exists an exception is thrown  Open – Opens an existing file. If file does not exist, an exception is thrown  OpenOrCreate – Opens a file if it exists or creates a new file if it does not exist  Truncate –Opens an existing file and truncates it to zero bytes (erases its contents)

The FileStream Class Members in the FileAccess enumeration  Read  ReadWrite  Write Members in the FileShare enumeration  None  Read  ReadWrite  Write Common method of the FileStream class  Close() Example Dim path as String = “C:\VB 2005\Files\Products.txt Dim fs as New FileStream(path, FileMode.create, FileAccess.Write)

The StreamReder Class The StreamReader and StreamWriter classes belong to the System.IO namespace Sequential files can be read one character at a time, one line at a time, or the entire file can be read at once Sequential files are typically read into a string or an array Closing a file disconnects the application from the file

The StreamReder Class The StreamReader constructor accepts one argument – the path and filename of the sequential file to open. Dim CurrentReader As StreamReader = _ New System.IO.StreamReader( _ "C:\Demo.txt") The Close method closes a sequential file. Always close files when processing is complete to prevent loss of data Open files also consume system resources Example: CurrentReader.Close()

The StreamReder Class The Close method closes an open file. The Peek method gets the next character without actually reading the character. The method returns the Integer code point of the character that will be read. The method returns -1 if there are no more characters to read The Read method reads a single character or many characters. Without arguments, the Read method returns the Integer code point of the character read The ReadLine method reads a record. The carriage return at the end of the record is discarded. The method returns a String containing the characters read. The ReadToEnd method reads from the current file position to the end of the file. The method returns a String containing the characters read

Reading Entire Content of File

Reading a Sequential File One Record at a Time Dim CurrentReader As New _ System.IO.StreamReader("C:\Demo.txt") Dim CurrentRecord As String CurrentRecord = CurrentReader.ReadLine() Do Until CurrentRecord = Nothing ' Statements to process the current record. CurrentRecord = CurrentReader.ReadLine() Loop CurrentReader.Close()

The StreamWriter Class The StreamWriter class of the System.IO namespace writes a sequential file The constructor accepts one argument – the file to write Example: Dim CurrentWriter As New _ System.IO.StreamWriter("C:\Demo.txt") ' Statements to write the file. CurrentWriter.Close()

The StreamWriter Class The NewLine property contains the character(s) that mark the end of the line The Close method closes the sequential file  It's imperative to close a sequential file once writing is complete to prevent loss of data The Write method writes a character or array of characters The WriteLine method writes data terminated by the character(s) stored in the NewLine property If the data type passed to Write or WriteLine is not a string, these methods will call toString  Individual variables must be concatenated and separators must be used

StreamWriter Example Code that writes data from a collection of Product objects to a text file Dim textOut As New StreamWriter( _ New FileStream( path, _ FileMode.Create, FileAccess.Write)) For Each product As Product In products textOut.Write(product.Code & "|") textOut.Write(product.Description & "|") textOut.WriteLine(product.Price) Next textOut.Close()

Writing a Freeform File A freeform file can be written all at once as follows: Dim StringData As String = "Freeform text" Dim CurrentWriter As New _ System.IO.StreamWriter("C:\Demo.txt") CurrentWriter.Write(StringData) CurrentWriter.Close()

Writing a Delimited File Write an array of Integers Public Shared Sub WriteIntegerList( _ ByRef argArray() As Integer, _ ByVal argFile As String) Dim CurrentStream As New StreamWriter(argFile) Dim CurrentIndex As Integer For CurrentIndex = 0 To argArray.GetUpperBound(0) CurrentStream.Write(argArray(CurrentIndex)) If CurrentIndex <> _ argArray.GetUpperBound(0) Then CurrentStream.Write(",") End If Next CurrentStream.Close() End Function

Example Declaring the BankUIForm

Example

Declaring Record class

Example Creating and writing sequential access file

Example

Example: Using LINQ with file

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

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. Exception Handling

fs = new FileStream(FileName, FileMode.Open, FileAccess.Read) FileName = “C:\test10.txt”

Because ex is an object variable, it now has its own Properties and methods. One of these is the Message property. Run your program and test it out. Click your button. You should see the following error message: Exception Handling

The point about this new message box is that it will not crash your program. You have handled the Exception, and displayed an appropriate message for the user. If you know the kind of error that a program might throw, you can get what Type it is from the Error message box you saw earlier. This one: Exception Handling

Click the View Details links under Actions to see the following:

The first line tells us the Type of Exception it is: System.IO.FileNotFoundException You can add this directly to the catch part. Previously, you were just catching any error that might be thrown: Catch ex As Exception But if you know a “file not found” error might be thrown, you can add that to the Catch line, instead of Exception: Catch ex As System.IO.FileNotFoundException You can keep the Exception line as well. (You can have as many Catch parts as you want.) This will Catch any other errors that may occur: Try fs = new FileStream(FileName, FileMode.Open, FileAccess.Read) Catch ex As System.IO.FileNotFoundException MsgBox(“Can’t find this file”) Catch ex As Exception MsgBox(ex.Message) End Try Exception Handling

There is one last part of the Try … Catch Statement that VB.NET doesn’t add for you  Finally: Try Catch ex As Exception Finally End Try The Finally part is always executed, whether an error occurs or not. You typically add a Finally part to perform any cleanup operations that are needed. For example, you may have opened a file before going into a Try … Catch Statement. If an error occurs, the file will still be open. Whether an error occurs or not, you still need to close the file. You can do that in the Finally part. Exception Handling