File Input and Output pdf

22 390 0
File Input and Output pdf

Đang tải... (xem toàn văn)

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

Thông tin tài liệu

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 Objectives 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 Chapter File Input and Output Implementing the File Input and Output Operations 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 NIIT File Input and Output 9.3 FileStream Class Most file Input/Output (I/O) support in the NET Framework is implemented in the 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 System.IO namespace 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 =new FileStream(,,,); 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 9.4 File Input and Output NIIT 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 NIIT File Input and Output 9.5 Implementing Reading and Writing in the Text Files 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 StreamReader Class 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 9.6 File Input and Output NIIT 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(); NIIT File Input and Output 9.7 } } 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 StreamWriter Class 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); 9.8 File Input and Output NIIT // 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 NIIT File Input and Output 9.9 Implementing Reading and Writing in Binary Files 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 BinaryReader Class 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 BinaryWriter 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); 9.10 File Input and Output NIIT The following table describes some of the commonly used methods of the BinaryWriter class Method Description Close Closes the current BinaryWriter and the underlying stream Seek Sets the position within the current stream Write Writes a value to the current stream Flush Clears all buffers for the current writer and causes any buffered data to be written to the underlying device Method of the BinaryWriter Class The following code snippet shows the implementation of the Binary Reading and Binary Writing classes to a file: using System; using System.IO; namespace BinaryData { public class RWData { public static void Main() { BinaryWriter dataout; BinaryReader datain; int i = 10; double d = 1023.56; bool b = true; dataout = new BinaryWriter(new FileStream("testdata",FileMode.Create)); Console.WriteLine("Writing " + i); dataout.Write(i); Console.WriteLine("Writing " + d); dataout.Write(d); Console.WriteLine("Writing " + b); dataout.Write(b); Console.WriteLine("Writing " + 12.2 * 7.4); dataout.Write(12.2 * 7.4); dataout.Close(); NIIT File Input and Output 9.11 Console.WriteLine(); // Now, read them back datain = new BinaryReader(new FileStream("testdata", FileMode.Open)); i = datain.ReadInt32(); Console.WriteLine("Reading " + i); d = datain.ReadDouble(); Console.WriteLine("Reading " + d); b = datain.ReadBoolean(); Console.WriteLine("Reading " + b); d = datain.ReadDouble(); Console.WriteLine("Reading " + d); } } Console.ReadLine(); datain.Close(); } 9.12 File Input and Output NIIT The following window shows the output of preceding code snippet Output of the Binary Reading Application 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 in a specific location DirectoryInfo Class The DirectoryInfo class is derived from the FileSystemInfo class The following table describes some of the commonly used properties of the DirectoryInfo class Property Description Attributes Gets or sets attributes associated with the current file This property is inherited from FileSystemInfo CreationTime Gets or sets CreationTime of the current file This property is inherited from FileSystemInfo Exists Gets a Boolean value indicating whether the directory exist or not Extension Gets a string containing the file extension This property is inherited from FileSystemInfo FullName Gets a string containing the full path of the directory This property is inherited from FileSystemInfo LastAccessTime Gets the last accessed time of the directory This property is inherited from FileSystemInfo Name Gets a string containing the name of a given file Properties of the DirectoryInfo Class 9.14 File Input and Output NIIT The following table describes some of the commonly used methods of the DirectoryInfo class Method Description Create Creates a directory CreateSubdirectory Creates a subdirectory Delete Deletes a directory GetDirectories Returns the directories in the current directory after matching all the criteria It also allows you to search subdirectories within directories GetFiles Returns the files in the current directory Methods of the DirectoryInfo Class The following code snippet shows how to create a DirecotryInfo object: DirectoryInfo MydirInfo = new DirectoryInfo (@"c:\WINDOWS"); Console.WriteLine ("Full Name of the directory is : {0}", MydirInfo.FullName); Console.WriteLine ("The directory was last accessed on : {0}", MydirInfo LastAccessTime.ToString ()); The preceding code snippet creates the DirectoryInfo object by the name MydirInfo The code snippet displays the full path to the directory and the time when the directory was last accessed FileInfo Class The FileInfo class is derived from the FileSystemInfo class The following table describes some of the commonly used properties of the FileInfo class Property Description Attributes Gets or sets attributes associated with the current file This property is inherited from FileSystemInfo CreationTime Gets 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 containing the full path of the file This property is inherited from FileSystemInfo LastAccessTime Gets the last accessed time of the file This property is inherited from FileSystemInfo LastWriteTime Gets the time of the last written activity to the file This property is inherited from FileSystemInfo Length Gets the size of the file Name Gets a string containing the name of a given file Properties of the FileInfo Class The following table lists some of the commonly used methods 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 { class Tester { public static void Main() { //Creating an instance of DirectoryInfo class DirectoryInfo MydirInfo = new DirectoryInfo(@"c:\WINDOWS"); // get all 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 their sizes NIIT File Input and Output 9.17 Practice Questions 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 = Console.ReadLine (); sw.Write (Str); sw.Flush (); sw.Close (); Fs.Close(); } } a b c d String str=Console.ReadLine(); sw.Write(Str); sw.Flush(); sw.Close(); You need to 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 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, 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 The method that is used to alter the positions from where a read or write operation can occur is _ Match the following terms in column B to the description in Column A A Attribute Gests a Boolean value indicating whether the directory exist or not Exits NIIT Gets or sets CreationTime of the current file CreationTime 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 learned that: A stream is an abstraction of 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 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 class Stream The Stream class is used to read and write data to the text files It is an abstract class, which supports reading and writing bytes into it The StreamReader class is inherited from the abstract class TextReader The TextReader class represents a reader which can read a series of characters The StreamWriter class is inherited from the abstract class TextWriter The TextWriter class represents a writer, which can write a series of characters The BinaryReader class allows reading of 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 Exercise David is a team leader of xyz organization He wants to create a scheduler, which will store fields, such as the appointment date, the name of the person to meet, and time He needs to develop an application that will enable the user to fill these fields The application should display certain options The options are: Add appointment: Should accept values such as appointment date, name of the person to be met, and time of the appointment View appointment: Should display all the appointments of the user Search: Should prompt the user to specify the date to view all the appointments of that day Exit: Allow the user to exit the application Hint: The date that the application should accept should be in the mm/dd/yyyy format Exercise You need to generate a program to play the Hangman game The program asks a user to enter a category as Book or Movie Based on the category provided, a book name or movie name is extracted and the user is asked to guess the name by giving the character and its position in the string NIIT File Input and Output 9.21 9.22 File Input and Output NIIT ... 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... from and write to any location within a file NIIT File Input and Output 9.3 FileStream Class Most file Input/ Output (I/O) support in the NET Framework is implemented in the You can use the FileStream... 9.12 File Input and Output NIIT The following window shows the output of preceding code snippet Output of the Binary Reading Application NIIT File Input and Output 9.13 Implementing the Windows File

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

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan