Managing Input/Output Files in Java
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make
input and output operation in java. A stream can be defined as a sequence of data. The InputStream is
used to read data from a source and the OutputStream is used for writing data to a destination.
InputStream and OutputStream are the basic stream classes in Java.
Why we need Stream classes?
To perform read and write operations on binary files we need a mechanism to read that binary data on
file/to write binary data (i.e. in the form of byte). These classes are capable to read and write one byte
on binary files. That’s why we use Stream Classes.
Types of streams:
Byte Stream : It provides a convenient means for handling input and output of byte.
Character Stream : It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.
1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to an output stream.
InputStream Classes - These classes are subclasses of an abstract class, InputStream and they are
used to read bytes from a source(file, memory or console).
Methods:
OutputStream Classes - These classes are subclasses of an abstract class, OutputStream and they
are used to write bytes to a destination(file, memory or console).
2. Character Stream:
Character stream is also defined by using two abstract classes at the top of the hierarchy, they are
Reader and Writer. These two abstract classes have several concrete classes that handle Unicode
characters.
Reader classes : Abstract class that define character stream input.
Writer classes : Abstract class that define character stream output.
Reading and Writing Bytes
Java supports the following I/O byte streams.
FileInputstream
FileOutputStream
The FileInputStream and FileInputStream classes are designed for reading and writing image
files as it reads and writes a stream of raw bytes.
FileInputstream: This class is a subclass of Inputstream class that reads bytes from a specified
file name. The read() method of this class reads a byte or array of bytes from the file. It returns
–1 when the end-of-file has been reached. We typically use this class in conjunction with
a BufferedInputStream and DataInputstream class to read binary data. To read text data, this
class is used with an InputStreamReader and BufferedReader class.
FileOutputStream: This class is a subclass of OutputStream that writes data to a specified file
name. The write() method of this class writes a byte or array of bytes to the file. We typically
use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to
write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and
an OutputStreamWriter class. This class throws FileNotFoundException, if the specified file
does not exist.
As an example, Program [Link] shows how to use the FileInputStream and
FileOutputStream classes to read and write files. It copies a file [Link] (which must exist in
the directory where we execute this program) to another file named [Link], which is
created if it does not exist.
[Link]
// Copying contents of one file into another using byte stream
import [Link].*;
public class FileTest03 {
public static void main(String[] args) {
File f1;
File f2;
FileInputStream in = null;
FileOutputStream out = null;
int c;
try {
f1 = new File("[Link]");
f2 = new File("[Link]");
in = new FileInputStream(f1);
out = new FileOutputStream(f2);
while((c = [Link]()) != -1) {
[Link](c);
catch(IOException e) {
[Link](e);
finally {
try {
[Link]();
[Link]();
catch(Exception e) {
[Link](e);
}
Let’s consider file [Link] has the following contents:
I am now writing Java I/O.
Happy Learning Friends.
It’s Good Bye from me.
If we run the program named [Link] then the contents of the above text
file [Link] will be copied to [Link] file. This example demonstrates that although
FileInputStream and FileOutputStream are more suitable to read and write image files, it is legal
to use them for text files too.
2. Reading and Writing Characters
However, the FileReader and FileWriter classes are more suitable to read and write streams of
characters (from text files). See the program ([Link]) below:
[Link]
// Copying content of one file into another using character stream
import [Link].*;
public class FileTest04 {
public static void main(String[] args) {
File f1;
File f2;
FileReader in = null;
FileWriter out = null;
int c;
try {
f1 = new File("[Link]");
f2 = new File("[Link]");
in = new FileReader(f1);
out = new FileWriter(f2);
while((c = [Link]()) != -1) {
[Link](c);
}
}
catch(IOException e) {
[Link](e);
}
finally {
try {
[Link]();
[Link]();
}
catch(Exception e) {
[Link](e);
}
}
}
}
The above program will generate the same output as program [Link] does: The
contents of the text file [Link] will be copied to [Link] file.
Handling Primitive Types
The basic input and output streams provide read and write methods that can only be used for
reading/writing bytes or characters. If we want to read and write the primitive data types such as
integers and doubles, we can use filter classes as wrappers on existing input and output streams to filter
data in the original stream. The two filter classes used for creating data streams for handling primitive
data types are DataInputStream and DataOutputStream.
A data stream for input can be created as follows:
DataInputStream dis = new DataInputStream(new FileInputStream(inFile));
Similarly, a data stream for output can be created as follows:
DataOutputStream dos = new DataOutputStream(new FileOutputStream(oFile));
The following program ([Link]) demonstrates the use of data streams for reading and writing
primitive data types. The program first creates [Link] file and then writes a few primitive data types
into it using DataOutputStream. At the end of writing, the stream is closed. The program also creates a
DataInputStream, connects it to [Link] file and displays them on the screen. Finally, it closes the
stream. See the program below:
[Link]
import [Link].*;
public class FileTest09 {
public static void main(String[] args) throws IOException {
File f = new File("[Link]");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
// Write primitive data
[Link](2019);
[Link](true);
[Link]('S');
[Link](99.95);
[Link]();
DataInputStream dis = new DataInputStream(new FileInputStream(f));
// Read primitive data
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]();
}
}
Output:
C:\file>java File09
2019
true
S
81.95
RandomAccessFile class
the RandomAccessFile class provided by the [Link] package. This is a class that allows us to read and
write arbitrary bytes, text, and primitive Java data types from or to any specified location in a file. As the
name suggests, random that means it is not sequential and the data can be read from and written to any
specified position in the file.
Mostly, Users use the input stream or output stream in a sequential but unlike the input and output
streams [Link] is used for both reading and writing files. A random access file treats
with a large array of bytes stored in the file system and uses the file pointer to deal with the index of
that array. This file pointer points the positions in the file where the reading or writing operation has to
be done.
RandomAccessFile class implements the same interfaces as the DataInputStream and the
DataOutputStream. Thus it defines the same methods for reading and writing data to a file.
This program shows the implementation of the RandomAccessFile class. The first part of the program
takes an input from user to the name of a file and checks if it exists then it writes the specified string
using the method writeChars(). Otherwise it displays the appropriate message as “File does not exist”.
An IOException may be thrown if the stream has been closed.
There are following methods has been used in this program:
RandomAccessFile rand = new RandomAccessFile(file,"rw");
The above code snippet creates an instance of the RandomAccessFile class mentioning the mode in
which file has to be opened. The constructor RandomAccessFile( ) takes two arguments: First is the file
name and another is the operation mode (read-write mode). We are opening the file into read and write
mode (“rw”).
There are following methods that are used in the given program ([Link]) shown as—
[Link]([Link]()): This is the seek( ) method of the RandomAccessFile class has been used to jump
the file position at the specified. Here, using [Link]() returns to the end of the file.
[Link](): This is the close( ) method of the RandomAccessFile class has been used to close the
created the instance of the RandomAccessFile class.
writeBytes( ): This the writeBytes( ) method which simply writes the content into the file. This method
always append the file content with our specified text.
readByte(): The second part of the program reads the characters from a file using
the readByte() method.
Here is the code of the program:
[Link]
import [Link].*;
public class FileTest14 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter File name : ");
String str = [Link]();
File file = new File(str);
RandomAccessFile rand = null;
if (![Link]()) {
[Link]("File does not exist.");
[Link](0);
}
//Open the file for both reading and writing
try {
rand = new RandomAccessFile(file, "rw");
[Link]([Link]()); //Seek to end of file
[Link]("Its Good Bye from Me."); //Write end of file
[Link]("Written Successfully!");
}
catch (IOException e) {
[Link]([Link]());
}
finally {
[Link]();
}
//Open the file for reading only
try {
rand = new RandomAccessFile(file, "r");
int n = (int) [Link]();
[Link]("Length: " + n);
[Link](0); //Seek to start point of file
[Link]("\nFile Contents:~ ");
for (int i = 0; i < n; i++) {
byte b = [Link](); //read byte from the file
[Link]((char) b); //convert byte into char
}
[Link]();
}
catch (IOException e) {
[Link]([Link]());
}
finally {
[Link]();
}
The output is shown here:
C:\file>java FileTest14
Enter File name : [Link]
Written Successfully!
Length: 76
File Contents:~
It's Merry Christmas..
Enjoy this festive season..
Its Good Bye from Me.