Page 370 - Cs_withBlue_J_C11_Flipbook
P. 370
Enter application no, name, ans average marks
10205 Ankit 99.6
Continue y/nn
Enter application number to search
10203
10203 Rajesh 99.5 Selected for Computer Sc. Hons.
12.4.3 Writing Data to a Text File
To write data to a text file, the following steps are to be followed:
Step 1: Create an object of the FileWriter class and connect it with the physical file on the disk. If the file does not
exist, then it is created by default. If it is already present on the disk then its previous contents are overwritten.
To avoid this, we can open in append mode by passing true as a parameter. In append mode, new records are
added at the end of the file.
FileWriter <fileobject> = new FileWriter("File name", true);
Step 2: Connect the FileWriter object with the BufferedWriter object. Buffers are temporary storage areas where the
output stream is first stored. Data in the buffer is generally transferred to the file when the buffer is full or
during the closing of the stream objects.
BufferedWriter <bufferobject> = new BufferedWriter(fileobject);
Step 3: Now, link the BufferedWriter object with the PrintWriter object for writing characters to the text file.
PrintWriter <printobject> = new PrintWriter(bufferobject);
Step 4: Write the text onto the file by using print() or println() method.
<printobject>.print(text) or <printobject>.println(text);
Step 5: Lastly, close all the stream objects using the close() method.
12.4.4 Reading Data from a Text File
To read data from a text file, the following steps are to be followed:
Step 1: Create an object of FileReader class and connect it with the physical file on the disk.
FileReader <fileobject> = new FileReader("File name");
Step 2: Connect the FileReader object with the BufferedReader object. Output buffers are temporary storage areas
that store a chunk of data read from the file. When the buffer is full, it is emptied and the next chunk of data
is stored.
BufferedReader <bufferobject> = new BufferedReader (fileobject);
Step 3: The text is read by invoking the method readLine() using BufferedReader object and stored in a String variable.
This object call should be inside the loop body which will return null, if the file does not exist or if the end of
file is reached.
String <variable> = <bufferobject>.readLine();
Step 4: Lastly, close all the stream objects using the close() method.
368368 Touchpad Computer Science-XI

