Page 363 - Cs_withBlue_J_C11_Flipbook
P. 363
Writer Class
The Writer class is also an abstract base class whose methods are implemented by its derived classes. Some of the
derived classes of the Writer class are described in the following table.
Class Description
BufferedWriter It provides methods to write characters to the buffer.
FileWriter It provides methods to write characters to the file.
PrintWriter It enables to print the formatted representation of objects to the text-output
stream. PrintWriter class has two overloaded methods:
• print(): Writes data on the same line.
• println(): Adds a new line character after writing data.
12.5 OPERATIONS ON FILES
Java allows us to perform various types of operations like writing data to a file and reading data from a file. We can
perform these operations on both binary as well as text files. Let us learn about them in detail.
12.5.1 Writing Data to a Binary File
Writing data to a file means transferring data in memory to a secondary storage device. Binary files can handle all
primitive data types and objects. To write data to a binary file, the following steps are to be performed:
Step 1: Create an object of the FileOutputStream class and connect it with the physical file on the disk. To open
in append mode, true parameter is used. If no parameter is specified then it will overwrite its previous
contents.
FileOutputStream <fileobject> = new FileOutputStream("File name", true);
Step 2: Connect the FileOutputStream’s object with the DataOutputStream’s object to call the required methods for
writing data of different primitive types.
DataOutputStream <dataobject> = new DataOutputStream(fileobject);
Step 3: Write data to the file using different write methods for different data types.
dataobject.writexxx(variable);
Step 4: Close all the stream objects by using the close() method.
fileobject.close();
12.5.2 Reading Data from a Binary File
Reading data from a file means transferring data from a secondary storage device to memory. To read data from a
Binary file, the following steps are to be followed:
Step 1: Create an object of FileInputStream class and connect it with the physical file on the disk.
FileInputStream <fileobject> = new FileInputStream("File name");
Step 2: Connect the FileInputStream object with the DataInputStream object to call the required methods for reading
data of different primitive types.
DataInputStream <dataobject> = new DataInputStream(fileobject);
Step 3: Read data from the file using different read methods for different data types inside a try-catch block. When
the end of file is met, an EOFException is generated which is handled by the catch block.
dataobject.readxxx(variable);
Step 4: Close all the stream objects as
object.close();
361
Basic Input/Output and Data File Handling 361

