File Input and Output pdf

22 366 0
  • Loading ...
    Loading ...
    Loading ...

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Tài liệu liên quan

Thông tin tài liệu

Ngày đăng: 01/08/2014, 09:21

File Input and Output Chapter 9 For information to be saved permanently on a disk, you can use a file. The file is a stream of characters or a flow of related data. Streams enable you to write and read bytes to and from a storage medium, respectively. Streams can be used to perform fundamental operations such as read and write. This chapter introduces the concept of the file input and output operations. It explains the process of reading and writing in the text files and the binary files. It also explains the process of browsing through the Windows File System. In this chapter, you will learn to:  Implement the file input and output operations  Implement read and write in text files  Implement read and write in binary files  Implement the Windows File System Objectives ¤NIIT File Input and Output 9.3 All programs accept input from a user, process the input, and produce an output. Therefore, all the programming languages support the input and output operations. For information to be saved permanently on a disk, you can use a file. The file is a collection of data stored on a disk with a specific name and very often with a directory path. When you open the file for reading data or writing data, it becomes a stream. The stream is a sequence of bytes travelling from a source to a destination over a communication path. The two basic streams used are the input and output streams. Each stream has a particular function. An input stream is used for a read operation and an output stream is used for performing a write operation. You can perform both these operations over the stream. The System.IO namespace includes various classes, which are used to perform operations, such as file creation, file deletion, and the read-write operations to files. The following table describes some commonly used classes in the System.IO namespace. Class Name Description FileStream Is used to read from and write to any location within a file BinaryReader Is used to read primitive data types from a binary stream BinaryWriter Is used to write primitive data types in binary format StreamReader Is used to read characters from a byte stream StreamWriter Is used to write characters to a stream StringReader Is used to read from a string buffer StringWriter Is used to write into a string buffer DirectoryInfo Is used to perform operations on directories FileInfo Is used to perform operations on files Common Class of System.IO Namespace In .NET, you can work with streams by using the FileStream class. This class supports random access to files, which means to read from and write to any location within a file. Implementing the File Input and Output Operations 9.4 File Input and Output ¤NIIT Most file Input/Output (I/O) support in the .NET Framework is implemented in the System.IO namespace. You can use the FileStream class in the System.IO namespace to read from, to write, and to close files. This class inherits from the abstract class Stream. Many of its properties and methods are also derived from the Stream class. To open an existing file or to create a new file, you need to create an object of type FileStream. Consider the following syntax for creating the object of type FileStream: FileStream <object name>=new FileStream(<file Name>,<FileMode Enumerator>,<File Access Enumerator>,<FileShare Enumerator>); Consider the following example for creating the object of type FileStream: FileStream File1= new FileStream (“Myfile.txt”, FileMode.Open, FileAccess.Read, FileShare.Read); In the preceding example, the FileMode, FileAccess, and FileShare enumerations define constants that are used by some of the FileStream and the IsolatedStorageFileStream constructors and some of the File.Open overloaded methods. These constants affect the way in which the underlying file is created, opened, and shared. FileMode Enumerator This enumerator defines various methods for opening files. The FileMode enumerator parameter is specified in many constructors for the FileStream, IsolatedStorageFileStream constructors, and in the Open methods of File and FileInfo to restrict how a file is opened. The parameters to FileMode checks whether a file is overwritten, created, or opened. The members of the FileMode enumerator are:  Append: Opens the file if it exists and places the cursor at the end of file, or creates a new file.  Create: Creates a new file.  CreateNew: Specifies to an operating system that is should create a new file.  Open: Opens an existing file.  OpenOrCreate: Specifies to the operating system that it should open a file if it exists; otherwise, it should create a new file.  Truncate: Opens an existing file. When opened, the file should be truncated so that its size is zero bytes. FileStream Class ¤NIIT File Input and Output 9.5 FileAccess Enumerator Unless you specify a FileAccess enumerator, the file gets opened for both reading and writing. This enumerator indicates whether you want to read data from the file, write to the file, or perform both the operations. The members of the FileAccess enumerator are Read, ReadWrite, and Write. FileShare Enumerator The FileShare enumerator contains constants for controlling the kind of access that the other FileStream constructors can have to the same file. A typical use of this enumeration is to define whether two different applications can simultaneously read from the same file. The members of the FileShare enumerator are:  Inheritable: Allows a file handle to pass inheritance to the child processes  None: Declines sharing of a current file  Read: Allows opening of a file for reading purpose  ReadWrite: Allows opening a file for the purpose of reading and writing  Write: Allows opening of a file for writing purpose 9.6 File Input and Output ¤NIIT The Stream class is used to read from and to write data in the text files. It is an abstract class, which supports reading and writing bytes into it. If data of a file is only text, then you can use the StreamReader class and the StreamWriter class to accomplish the reading and writing tasks, respectively. The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader which can read a series of characters. The following code implements the StreamReader class: FileStream fs = new FileStream("Myfile.txt", FileMode.Open,FileAccess.Read); StreamReader sr = new StreamReader(fs); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); In the preceding code, the Seek() method allows the read/write position to be moved to any position within the file. This method takes two parameters, a byte position and a reference point. The byte position is relative to the reference point. The reference point can be Begin, Current, or End. These reference points are represented by the properties of the SeekOrigin class. The reference point, Begin, provides the seek reference position as the beginning of the stream. Current provides the seek reference position as the current position within the stream and the reference point. End, provides the seek reference position as the end of the stream. The objects of the FileStream class are used to provide random access to files. The FileStream constructor takes parameters that are used to initialize the members of the class. Implementing Reading and Writing in the Text Files StreamReader Class ¤NIIT File Input and Output 9.7 The following table describes some of the commonly used methods of the StreamReader class. Methods Description Close Closes the object of StreamReader class and the underlying stream, and releases any system resources associated with the reader Peek Returns the next available character but does not consume it Read Reads the next character or the next set of characters from the stream. ReadLine Reads a line of characters from the current stream and returns data as a string Seek Allows the read/write position to be moved to any position within the file Methods of the StreamReader Class The following code snippet implements the StreamReader class to read data from the file: using System; using System.IO; class FileRead { public void ReadData() { FileStream fs = new FileStream("Myfile.txt", FileMode.Open,FileAccess.Read); StreamReader sr = new StreamReader(fs); //Position the file pointer at the beginning of the file sr.BaseStream.Seek(0, SeekOrigin.Begin); //Read till the end of the file is encountered string str = sr.ReadLine(); while (str != null) { Console.WriteLine("{0}", str); str = sr.ReadLine(); } // close the writer and underlying file sr.Close(); fs.Close(); } public static void Main(String[] args) { FileRead fr = new FileRead(); fr.ReadData(); 9.8 File Input and Output ¤NIIT } } In the preceding code, the FileMode property value is Open and the FileAccess property value is Read. This opens the file, Myfile.txt, in the open mode and prepares the stream for a read operation. The statement, StreamReader sr=new StreamReader(fs), creates a new instance of the StreamReader class for Myfile.txt. In addition, code reads from Myfile.txt. The Seek() method allows the read position to be moved to the beginning of a file and read till the end of the file. The StreamWriter class is inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters. The following table describes some of the commonly used methods of the StreamWriter class. Methods Description Close Closes the current StreamWriter object and the underlying stream Flush Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream Write Writes to the stream WriteLine Writes data specified by the overloaded parameters, followed by end of line Methods of the StreamWriter Class The following code implements the StreamWriter class to accept data from a user and write the same into the file: using System; using System.IO; class FileWrite { public void WriteData() { //object of filestream class is created FileStream fs = new FileStream("Myfile.txt", FileMode.Append, FileAccess.Write); StreamWriter w = new StreamWriter(fs); StreamWriter Class ¤NIIT File Input and Output 9.9 // Prompting user to enter the string which needs to be stored in //the file. Console.WriteLine("Enter a string"); //Reads the string entered by the user and stores in str string str = Console.ReadLine(); //Writes the string entered by the user in the file Myfile.txt. w.Write(str); // Clears all buffer of the current writer w.Flush(); //Closes the current StreamWriter object. w.Close(); fs.Close(); } public static void Main(String[] args) { FileWrite fw = new FileWrite(); fw.WriteData(); } } In the preceding code, the FileMode property value is Append and the FileAccess property value is Write. This opens the file, Myfile.txt, in the append mode and prepares the stream for a write operation. The statement, StreamWriter w=new StreamWriter(fs), creates a new instance of the StreamWriter class for Myfile.txt. In addition, code accepts input from a user and writes the contents to Myfile.txt. The functions that can be used for the write operations are Write() and WriteLine(). The difference between Write() and WriteLine() operations is that the Write() method is used to display the specified information on the output destination while the WriteLine() method is used to display the information followed by a line terminator. The Flush() method clears the stream buffer. The Close() method closes the stream and releases any resources associated with the current stream. 9.10 File Input and Output ¤NIIT All the information stored in the text format would be displayed on a screen as text. This means 'A' will be written as 'A' in the files. Similarly, the number –12345.678 will be written as the string "-12345.678". This means that you can directly display the contents of the file on the screen. Binary read and write means that the number –12345.678 is written as a float representation consuming four bytes of space. The BinaryReader and BinaryWriter classes are used for reading and writing the binary data in to files. The BinaryReader class is used to read binary data from a file. You can create BinaryReader object by passing its constructor, a FileStream object, as shown in the following code snippet: FileStream fs = new FileStream(@"C:\TEST2.DAT",FileMode.Open,FileAccess.Read); BinaryReader br = new BinaryReader(fs); The following table describes some of the commonly used methods of the BinaryReader class. Method Description Close Closes the current reader and the underlying stream Read Reads characters from the underlying stream and advances the current position of the stream Methods for the BinaryReader Class The BinaryWriter class is used to write binary data to a stream. You can create a BinaryWriter object by passing its constructor, a FileStream object, as shown in the following code snippet: FileStream fs = new FileStream(@"C:\TEST2.DAT",FileMode.CreateNew); BinaryWriter bw = new BinaryWriter(fs); Implementing Reading and Writing in Binary Files BinaryReader Class BinaryWriter Class [...]... of the FileInfo class and their functions Method Function Create Creates a file AppendText Appends a text to the file represented by the FileInfo object Delete Deletes a file Open Opens file OpenRead Opens a file in read-only mode Methods of the FileInfo Class 9.16 File Input and Output NIIT The following code shows the use of the FileInfo class: using System; using System.IO; namespace File_ Handling... the files in the directory and // print their name, and size FileInfo [] FilesInDir = MydirInfo.GetFiles ( ); foreach (FileInfo file in FilesInDir) { Console.WriteLine ( "File Name :{0} Size: {1} bytes", file. Name, file. Length); } } } } In the preceding code, the GetFiles() method is used to retrieve the list of all the files in the directory This code displays the list of all the files the directory and. .. access a file named MyFile.txt If the file already exists on the system, you need to open it; else you need to ensure that a new file with the file name MyFile.txt is created Which of the following statements would you write to do the preceding task? a b c d FileStream Fs = new FileStream("c:\\MyFile.txt", FileMode.Create, FileAccess.Write); FileStream Fs = new FileStream("c:\\MyFile.txt", FileMode.CreateNew,... FileMode.Create, FileAccess.Write); FileStream Fs = new FileStream("c:\\MyFile.txt", FileMode.CreateNew, FileAccess.Write); FileStream Fs = new FileStream("c:\\MyFile.txt", FileMode.Open, FileAccess.Write); FileStream Fs = new FileStream("c:\\MyFile.txt", FileMode.OpenOrCreate, FileAccess.Write); 9.18 File Input and Output NIIT 3 The method that is used to alter the positions from where a read or write operation... NIIT File Input and Output 9.13 Implementing the Windows File System The ability to browse and locate files and directories for a specific directory is essential for many programming tasks You can work with files and directories by using classes such as the DirectoryInfo and FileInfo classes in combination Using these classes is an efficient way to gather the required information about files and directories... binary data from a file The BinaryWriter class allows writing of binary data to a stream The DirectoryInfo class is derived from FileSystemInfo class and it works on a specific directory and shows the fullpath of the current directory The FileInfo class is derived from FileSystemInfo class and it works on a specific directory to display the list of all the files 9.20 File Input and Output NIIT Exercises... path The two basic streams used are the input and output streams An input stream is used for a read operation and an output stream is used for performing a write operation Most file I/O support in the NET Framework is implemented in the System.IO namespace You can use the FileStream class in the System.IO namespace to read from, to write, and to close files The FileStream class inherits from the abstract... NIIT Gets or sets CreationTime of the current file CreationTime 5 B Gets or sets attribute associated with the current file This property is inherited from FileSystemInfo John wants to perform a read/write operation on a file He does not want the file to be overwritten when he is performing the write operation Which FileMode should he use? File Input and Output 9.19 Summary In this chapter, you have... or sets CreationTime of the current file This property is inherited from FileSystemInfo Directory Gets an instance of the directory which the file belongs to NIIT File Input and Output 9.15 Property Description Exists Gets a boolean value indicating whether the file exists or not Extension Gets a string containing the file extension This property is inherited from FileSystemInfo FullName Gets a string... displays the list of all the files the directory and their sizes NIIT File Input and Output 9.17 Practice Questions 1 Which method in the following code writes the input to the stream? using System; using System.IO; class Write { public static void Main (String[] args) { FileStream Fs=new FileStream (“MyFile.txt”, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter (fs); String str . which means to read from and write to any location within a file. Implementing the File Input and Output Operations 9.4 File Input and Output ¤NIIT Most file Input/ Output (I/O) support in the. the file input and output operations  Implement read and write in text files  Implement read and write in binary files  Implement the Windows File System Objectives ¤NIIT File Input and. FileStream: FileStream File1 = new FileStream (“Myfile.txt”, FileMode.Open, FileAccess.Read, FileShare.Read); In the preceding example, the FileMode, FileAccess, and FileShare enumerations define
- Xem thêm -

Xem thêm: File Input and Output pdf, File Input and Output pdf, File Input and Output pdf