Java IO Stream

Java IO Streams with Examples

In this article, I am going to discuss Java IO Streams in detail with Examples. Please read our previous article where we discussed JVM Architecture in detail. As part of this article, you will understand the following pointers in detail which are related to Java IO Streams.

  1. Why we need IO Streams?
  2. Where we can store the data or result permanently?
  3. How a java application can store and read data from a file?
  4. What is a Stream object?
  5. What are Streams in Java?
  6. Standard Streams in Java
  7. Types of IO Streams in Java
  8. What are the different sources and destinations to read and write data?
  9. How can we create a Stream in java Specific to source and destination?
  10. Byte Streams in Java
  11. Character Streams in Java
Why we need IO Streams in Java?

The basic need for IO Streams is to

  1. Storing and reading data from files
  2. Also reading data from the keyboard
First, let us understand some basic terminology:

Persistence media: The environment that allows us to store data permanently is called persistence Media. We can store data permanently in places, such as

  1. File
  2. Database
  3. Remote computer (Socket)

Persistence: The process of storing data permanently in persistence media is called persistence

Persistence logic: The logic that persists data in persistent media is called persistence logic. For example, IOStream based logic, JDBC-based Logic, Networking based logic.

Persistence Technologies: The technology that provides API to develop persistence logic is called persistence technology. Well, known persistence technologies are IOStream to persist data in files, JDBC, EJB, HIBERNATE to persists data in the database, Networking to persist data in Remote Computer.

Where we can store the data or result permanently?

In persistence Media either in files or databases. Storing data in variable and array is temporary. Data will be lost when a local variable goes out of scope or when the program terminates. The programmer uses files or databases for long-term storage of a large amount of data. It is available even after the termination of the program.

To store data in files and Databases SUN has given in-built APIs. We all need to creating a particular class object and calling methods on that object for storing and reading data from that persistence media.

IOStream API is given to store and read data from files. JDBC API is given to store and read data from databases. For better understanding please have a look at the below diagram.

Java IO Streams with Examples

In this chapter, we will learn how to store data in files using the IOStream API. In the JDBC chapter, we will also learn how to store data in the database using the JDBC API.

Note: in either of the approaches we just create objects of the predefined classes and we will call appropriate methods to store and read data from files and databases. So IOStreams API and JDBC API are given not for developing business logic rather they are given to develop persistence logic.

How a java application can store and read data from a file?

Using Stream object.

What is a Stream object?

The stream is a logical connection between a java program and a file. To store the data in the persistence media there should be a way to connect to persistence media from java application either physically or logically. Stream provides a logical connection. So we can define the stream as “it is a continuous flow of data between java program and persistence media”.

Java Input Output Stream:

Java IO streams are flows of data you can either read from or write to. An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

What is Input (I)?

Input means taking the data into our application which is nothing but reading data. Example – command-line arguments, files, network, gamepads, keyboard, mouse, temperature sensor, webcam, other processes, etc.

Java Input Stream

What is Output (O)?

Output means giving the data out from our application which is nothing but writing data. Example – files, network, gamepad rumble, monitor, LEDs, speakers, robot motor, etc.

Java Output Stream

What are Streams in Java?

Streams meaning is the flow of data from one location to another location. A stream is a data structure facilitating the handling of an information source for sequential access. Programs read from and write to streams, and not the actual source or destination.

Standard Streams in Java:

In Java, 3 streams are created for us automatically. All these streams are attached to the console.

System.out (standard output stream): This is used to feed the data to the user’s program and usually a keyboard is used as a standard input stream and represented as System.in.

System.in (standard input stream): This is used to output the data produced by the user’s program and usually a computer screen is used for standard output stream and represented as System.out.

System.err (standard error stream): This is used to output the error data produced by the user’s program and usually a computer screen is used for standard error stream and represented as System.err.

What are Streams in Java

IO Stream in Java

IO Streams are mainly used to transfer the data from one location to another location. IO streams meant for performing reading operation from or writing operation onto any IO Devices.

Types of IO Streams in Java:

Generally, Streams are divided into two types based on the data flow direction, such as

  1. InputStream
  2. OutputStream

The stream that allows the data to come into the java application from the persistent media is called an input stream. The stream that allows the data to send out from the java application to be stored into the persistent media is called an output stream.

Basically, InputStreams are used to read data from persistent media, and Output Streams are used to write or store data in a persistent media from the java application. But according to the types of data passed through streams, java streams are divided into two types. They are

  1. Binary Stream
  2. Character Stream

The stream which reads and writes the data in the form of bytes is called Binary Streams. The Stream which reads and writes the data in the form of the character is called a character stream. The below diagram shows the type of stream

Types of IO Streams in Java

What are the different sources and destinations to read and write data?

The data can be read from different sources and also data can be written into different destinations. From sources, the java application reads data and it writes data to the destinations.

What are the different sources and destinations to read and write data

The sources can be a keyboard, mouse, file, Database, socket(computer), object, array, string, etc. The Destinations can be monitor, File, database, Socket(computer), Object, array, string, etc.

How can we create a Stream in java Specific to source and destination?

In the java.io package, we have several classes to create input and output streams specific to source and destination. So the technical definition of the stream would be “Stream is a java Object that allows reading and writing data to a persistence media”.

Byte Streams in Java:

Byte Streams are used to transfer the data from one location to another location byte by byte. Byte Streams can handle any kind of files like images, audio files, text files, etc…

Types of Byte Streams

In Java, Byte Streams are again classified into the following two types:

  1. InputStream
  2. OutputStream
InputStream

Input Stream is the super most class of all classes which are used for performing reading operations from any input device byte by byte. The InputStream class of the java.io package is an abstract superclass that represents an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.

Syntax : InputStream object1 = new FileInputstream();

Subclass of InputStream

Subclass of InputStream in Java

OutputStream

Output Stream is the super most class of all classes that are used for performing writing operations from any output device byte by byte. The OutputStream class of the java.io package is an abstract superclass that represents an output stream of bytes. Since OutputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to write data.

Syntax : OutputStream object = new FileOutputStream();

Subclass of OutputStream

Subclass of OutputStream in Java

Example to demonstrate Byte InputStream and OutputStream in Java:
import java.io.*;
public class InputOutputStream
{
  public static void main (String[]args)
  {
    try
    {
        byte bWrite[] = { 11, 21, 3, 40, 5 };
        OutputStream os = new FileOutputStream ("test.txt");
        for (int x = 0; x < bWrite.length; x++)
     {
         os.write (bWrite[x]);	// writes the bytes
     }
        os.close ();

        InputStream is = new FileInputStream ("test.txt");
        int size = is.available ();

        for (int i = 0; i < size; i++)
     {
         System.out.print ((char) is.read () + "  ");
     }
        is.close ();
    } 
    catch (IOException e)
    {
        System.out.print ("Exception");
    }
  }
}

The above code would create file test.txt and would write given numbers in binary format. The same would be the output on the stdout screen.

Character Streams in Java

Character Streams are used to transfer the data from one location to another location char by char. Byte streams can handle only text files hence these streams can also be called text streams. Character Streams are faster than Byte Streams.

Types of Character Streams

In Java, Character Streams are also classified into the following two types:

  1. Reader
  2. Writer
Reader Character Stream in Java

The reader is the super most class of all classes which are used for performing reading operations from any input device char by char. The Reader class of the java.io package is an abstract superclass that represents a stream of characters. Since Reader is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.

Syntax : Reader input = new FileReader();

Sub classes of Reader

Sub classes of Reader in Java

Writer Character Stream in Java

The writer is the super most class of all classes that are used for performing writing operations from any output device char by char. The Writer class of the java.io package is an abstract superclass that represents a stream of characters. Since Writer is an abstract class, it is not useful by itself. However, its subclasses can be used to write data.

Syntax : Writer output = new FileWriter();

Subclasses of Writer

Subclasses of Writer in Java

Example to demonstrate Character Reader and Writer Stream in Java:
import java.io.*;
public class InputOutputStreamExample
{
  public static void main (String[]args) throws IOException 
  {
    try
    {
        //Creating FileReader object
        File file = new File("E:/TextFile1.txt");
        FileReader reader = new FileReader(file);
        char chars[] = new char[(int) file.length()];
        //Reading data from the file
        reader.read(chars);
        
        //Writing data to another file
        File out = new File("E:/TextFile2.txt");
        FileWriter writer = new FileWriter(out);
        //Writing data to the file
        writer.write(chars);
        writer.flush();
        System.out.println("Data successfully written to the specified file");
    } 
    catch (IOException e)
    {
        System.out.print ("Exception" + e.getMessage());
    }
  }
}

Output: Data successfully written to the specified file

In the next article, I am going to discuss the Java Byte Streams in detail with examples. Here, in this article, I try to explain Java IO Streams with Examples. I hope you enjoy this Java IO Streams with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Java IO Streams with Examples article.

Registration Open For New Online Training

Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.

Leave a Reply

Your email address will not be published. Required fields are marked *