1. Trang chủ
  2. » Công Nghệ Thông Tin

File Input and Output pdf

22 390 0
Tài liệu được quét OCR, nội dung có thể không chính xác

Đ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

Thông tin cơ bản

Định dạng
Số trang 22
Dung lượng 594,54 KB

Nội dung

Trang 1

File Input and Output

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

Trang 3

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 10 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 ¡1O 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 String Writer 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 10 Namespace

Trang 4

FileStream Class

Most file Input/Output (I/O) support 1n the NET Framework is implemented in the System 10 namespace You can use the FileStream class in the System 10 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 Filel= 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

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

w Inheritable: Allows a file handle to pass inheritance to the child processes w® None: Declines sharing of a current file

w Read: Allows opening ofa file for reading purpose

Trang 6

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 St reamReader class and the StreamWriter class to accomplish the reading and writing tasks, respectively

StreamReader Class

The St reamReader 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 St reamReader 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

Trang 7

The following table describes some of the commonly used methods of the st reamReader 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 St reamReader Class

The following code snippet implements the StreamReader class to read data from the file: using System; using System.10; class FileRead { public void ReadData () { FileStream fs = new FileStream("Myfile.txt", FileMode.Open, FileAccess.Read) ;

StreamReader sr = new StreamReader(fs);

Trang 8

}

In the preceding code, the FileMode property value is Open and the FileAccess property value 1s 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 St reamReader 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 Stream riter 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 St reamWriter 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 St reamWriter 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.10; class FileWrite { public void WriteData() {

//object of filestream class is created

FileStream fs = new FileStream("Myfile.txt", FileMode.Append,

FileAccess.Write);

Trang 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 Fi 1eMode 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

Trang 10

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) ;

Trang 11

The following table describes some ofthe commonly used methods of the Bi nazyWzitez 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 BinarywWriter Class

The following code snippet shows the implementation of the Binary Reading and Binary Writing classes to a file: using System; using System.10; namespace BinaryData { public class RWData { public static void Main() { BinaryWriter dataout; BinaryReader datain; int 1 = 10; double d = 1023.56; bool b = true; dataout = new

BinaryWriter (new FileStream("testdata", FileMode.Create) );

Trang 13

The following window shows the output of preceding code snippet

cx file: ///C:/DataFiles/BinaryData/Binar yData/bin/Debug/BinaryData EXE

Trang 14

Implementing the Windows File System

The ability to browse and locate files and directories for a specific directory 1s 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 1s derived from the FileSystemiInfo class The following table describes some of the commonly used properties of the Di rectoryInfo class Property Description

Attributes Gets or sets attributes associated with the current file This property is inherited from FileSystemInfo

_ Gets or sets CreationTime of the current file This property is CreationTime inherited from FileSystemInfo ý J properly Exists Gets a Boolean value indicating whether the directory exist or not

Gets a string containing the file extension This property is

Extension ‘ & con g the fi property

inherited from FileSystemInfo

FullName Gets a string containing the full path of the directory This property is inherited from FileSystemInfo

Gets the last accessed time of the directory This property is LastAccessTime inherited from FileSystemInfo ý ở properly Name Gets a string containing the name of a given file

Trang 15

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 Returns the directories in the current directory after matching all GetDirectories the criteria It also allows you to search subdirectories within directories GetFiles Returns the files in the current directory

Methods of the Di rectoryInfo 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 : {Q}", MydivrInfo FullName) ;

Console.WriteLine ("The directory was last accessed on : {0}", MydiriInfo LastAccessTime.ToString ());

The preceding code snippet creates the DirectoryInfo object by the name Mydi z1n£o The code snippet displays the full path to the directory and the time when the directory was last accessed

Filelnfo 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

Gets or sets CreationTime of the current file This proper

CreationTime — ⁄ ji properly

is inherited from FileSystemInfo

Directory Gets an instance of the directory which the file belongs to

Trang 16

Property Description Exists Gets a boolean value indicating whether the file exists or not

Gets a string containing the file extension This property is

Extension Jee & con g the fi property

inherited from FileSystemInfo

Gets a string containing the full path of the file This

FullName property is inherited from FileSystemInfo Ing com & J path of the fi

Gets the last accessed time of the file This property is LastAccessTime inherited from FileSystemInfo 7 thẻ ƒi properly

or: Gets the time of the last written activity to the file This LastWriteTime property is inherited from FileSystemInfo ý 3 I Length Gets the size of the file

Name Gets a string containing the name of a given file The following table lists some of the commonly used methods of the FileInfo class and their functions Properties of the FileInfo Class Method Function

Create Creates a file

AppendText kinh a text to the file represented by the FileInfo Delete Deletes a file

Open Opens file

OpenRead Opens a file in read-only mode

Methods of the FileInfo Class

Trang 17

The following code shows the use of the FileInfo class: using System; using System.10; namespace File Handling { class Tester { public static void Main() {

//Creating an instance of DirectoryInfo class DirectoryInfo MydiriInfo = new

DirectoryInfo(@"c:\WINDOWS") ;

// get all the files in the directory and

// print their name, and size

FileInfo [] FilesInDir = MydiriInfo.GetFiles ( );

foreach (FileInfo file in FilesInDir) { Console.WriteLine ("File Name file.Name, file.Length); } } Size: {1} bytes",

Trang 18

Practice Questions 1 Which method in the following code writes the input to the stream? using System; using System.10; 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() } } f f a String str=Console.ReadLine(); b sw.Write (Str); Cc sw.Flush(); d sw.Close();

2 You need to access a file named MyFile.txt Ifthe 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 1s created Which of the following statements would you write to do the preceding task?

Trang 19

3 The method that is used to alter the positions from where a read or write operation can occur 1s

4 Match the following terms in column B to the description in Column A A B Attribute Gets or sets CreationTime of the current file

CreationTime Gests a Boolean value indicating whether the directory exist or not

Exits Gets or sets attribute associated with the current file This property is inherited from FileSystemInfo

Trang 20

Summary

In this chapter, you have learned that:

A stream 1s 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 10 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 1s inherited from the abstract class TextReader The TextReader class represents a reader which can read a series of characters

The StreamWriter class 1s 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

Trang 21

Exercises

Exercise 1

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:

m 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

m 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 2

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

TỪ KHÓA LIÊN QUAN

w