Basic I/O Operations in Java (Input/Output Streams)

Read through our Complete Java training series to gain more insight on Java concepts. Using a java program, you can read and write data from different sources and destinations.

Reading and writing data sources and destinations include:

Files

Pipes

Network Connections

In-memory Buffers (E.g: arrays)

System.in, System.out, System.error

In this tutorial, we will have the input as file and explore various classes, interfaces, and methods that are available to read data from the file.

Watch the below video tutorial on:

Basic IO Operations in Java:

Java File Operations:

Input/Output Streams

Streams represent the flow of data and that data can be in any format (like byte, text, primitive data type etc). To write data into a destination, the output stream is used and in order to read the data, the input stream is used.

Different formats of Reading and Writing:

Input/output can be read/write as the following different formats:

#1) Reading file as Byte Streams:

Here the data will be read in byte format. “FileInputStream” and “FileOutputStream “classes are used for reading the content as a byte. In this way, for every byte, the compiler will send a request to the OS.

In this way, the input stream will be read in character format. So, for each character, the compiler will send a request to the OS. “FileReader” and “FileWriter” classes are useful for reading the content as the character.

When you use the FileInputStream or FileReader classes, for every read or write operation, a new request will be sent to OS. So, this may lead to performance issue. In order to avoid this BufferedInputStream or BufferedReader, classes are used to wrap unbuffered classes.

This reads the input stream when the buffer is empty.

Likewise, FileOutputStream or FileWriter, classes are wrapped with BufferedOutputStream or BufferedWriter to write the output once the buffer is full.

In this method, the DataInputStream or DataOutputStream, classes are used to read and write the content as primitive data type such us boolean, char, byte, short, int, long, float, double and String. Mostly the DataInputStream and DataOutputStream will be used together.

ObjectInputStream/ ObjectOutputStream, classes are useful to write objects in a file and read the objects from the file. For storing the object in a file, the class should implement the Serializable interface.

You can read/write data in a different format like byte, character, object, primitive data type.

File class is used to create a file, delete the file and Move or copy or rename the file.

BufferedInputStream or BufferedOutputStream are used to improve the performance by buffering the data.

Conclusion

In this tutorial, we explored the various format of data reading /writing and the classes, interfaces, methods available to perform operations on the various format of data and also about the file operations.