Table of contents
1.
Introduction
2.
What are I/O Streams in Java?
3.
Why We Need I/O Streams in Java?
4.
Standard I/O Streams in Java
4.1.
Standard Input Stream (System.in)
4.2.
Java
4.3.
Standard Output Stream (System.out)
4.4.
Java
4.5.
Standard Error Stream (System.err)
5.
Types of Streams
5.1.
Input Streams
5.2.
Output Streams
5.3.
Byte Streams
5.4.
Java
5.5.
Character Streams
6.
Frequently Asked Questions
6.1.
What do you mean by I/O in Java?
6.2.
Is I/O a package in Java?
6.3.
When to use Java I/O?
6.4.
How to handle I/O errors in Java?
6.5.
What are the two streams of Java I/O?
7.
Conclusion
Last Updated: Nov 3, 2024
Easy

Introduction to Java I/O Streams

Author Vasu Bansal
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss Input/Output operations in Java. This is one of the first steps that one needs to learn while learning a new programming language. It helps the programmers communicate with the users by taking inputs from the users and displaying outputs on their screens.

Introduction to Java I/O Streams

Must Read, Multithreading in java, Duck Number in Java

What are I/O Streams in Java?

I/O streams in Java are abstractions that allow for reading from and writing to data sources, such as files, network connections, or memory. They are divided into two main categories: Input Streams and Output Streams.

  • Input Streams are used to read data from a source, such as FileInputStream for reading files or BufferedInputStream for reading data in a more efficient manner.
  • Output Streams are used to write data to a destination, such as FileOutputStream for writing to files or BufferedOutputStream for efficient writing.

Java's I/O streams provide a flexible framework for handling various types of data, facilitating operations such as file manipulation, data serialization, and inter-process communication.

Why We Need I/O Streams in Java?

I/O streams in Java are essential for several reasons:

  1. Data Manipulation: They provide a standardized way to read from and write to various data sources, allowing for effective data manipulation.
  2. Abstraction: Streams abstract the underlying details of how data is accessed and stored, enabling developers to focus on the application logic rather than the complexities of data handling.
  3. Performance Optimization: Java provides different types of streams that optimize performance for specific tasks, such as buffered streams for efficient reading and writing.
  4. Cross-Platform Compatibility: I/O streams ensure that Java applications can handle data input and output consistently across different platforms, enhancing portability.

Standard I/O Streams in Java

There are three standard I/O streams in Java. They are discussed below.

Standard Input Stream (System.in)

The standard input stream is used to take input from the user in a program. The input destination can be specified in the program itself. For example, the input can be read from a file, or it can be read as the input supplied by the user from the keyboard. The following program takes input from the user and displays the result on the output screen.

Code:

  • Java

Java

import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
     
       InputStreamReader input_stream_reader = null;
     
       try{
           input_stream_reader = new InputStreamReader(System.in);

           System.out.println("Enter a string of characters. Type letter x to exit");

           char input;

           while(true) {

               input = (char) input_stream_reader.read();

               if(input == 'x'){
                   break;

               }

               else{
                   System.out.print(input);

               }
           }
       }
       catch(Exception e){

           System.out.println("Exception is: ");

           System.out.println(e);

       }     
       finally{
           if (input_stream_reader != null) {

               input_stream_reader.close();

               System.out.println("\nInput Stream Reader closed");

           }
       }
     
   }
}
You can also try this code with Online Java Compiler
Run Code

Input:

Welcome to Coding Ninjas x

Output:

Enter a string of characters. Type letter x to exit
Welcome to Coding Ninjas
Input Stream Reader closed

Standard Output Stream (System.out)

The standard output stream is used to display some message or information to the user on the output screen or some specified destination. It used the functions print, println and printf to do the task. The following program gives examples of all these three standard output functions in Java.

Code:

  • Java

Java

import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
     
       System.out.print("print method called");

       System.out.println("println method called");

       int num = 10;
     
       System.out.printf("The value of num is %d\n", num);
     
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

print method called
println method called
The value of num is 10

Standard Error Stream (System.err)

This stream is used to throw all errors that may arise in a program when it is running. This stream also uses the function used by standard output stream i.e. print(), printf() and println(). The concept is very similar to the STDERR header defined in the C++ programming language, in case you are familiar with that language.

Must Read: Java System Out Println and Hashcode Method in Java

Types of Streams

The following are the different types of streams present in Java. These stream classifications are made on different parameters, as discussed below.

Input Streams

This classification is done based on the type of operation performed by the stream. This stream class is the superclass of each I/O class in Java. They help read data from the input, which may be a terminal or a file. 

Output Streams

This classification is also done based on the type of operation performed by the stream. This stream class is used to write data to the destination. The destination could be your monitor, a file on the system, an array, etc. Some examples include FileOutputStream, ByteArrayOutputStream, BufferedOutputStream, etc.

Byte Streams

This classification of the stream is based on the type of files. This stream is used for byte by byte processing of data. There are many classes of this stream. Some of them are listed below.

  • FileInputStream
  • FileOutputStream
  • BufferedInputStream
  • BufferedOutputStream
  • DataInputStream
  • DataOutputStream
  • InputStream
  • OutputStream
  • PrintStream
     

Code:

  • Java

Java

// Java program to demonstrate Byte Streams
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
   public static void main(String[] args) throws IOException {
     
       FileInputStream input_stream = null;
     
       FileOutputStream output_stream = null;
     
       try{

           // FileInputStream and FileOutputStream are related to byte streams
         
           input_stream = new FileInputStream("input_file.txt");

           output_stream = new FileOutputStream("output_file.txt");
       
           int data;
         
           while(true) {
             
               data = input_stream.read();
             
               if(data != -1){
                 
                   output_stream.write(data);

               }
             
               else{

                   break;

               }
           }

       }

       catch(Exception e){

           System.out.println("Exception is: ");

           System.out.println(e);

       }
     
       finally{

           if (output_stream != null) {
             
               output_stream.close();
             
               System.out.println("Output stream closed");

           }

           if (input_stream != null) {
             
               input_stream.close();
             
               System.out.println("Input stream closed");

           }
       }
     
   }
}
You can also try this code with Online Java Compiler
Run Code

Input:

In a file named input_file.txt, give the following text.

Output:

The following output will appear in the file named output_file.txt

The following output will appear on the terminal screen

Output stream closed
Input stream closed


Practice by yourself on java online compiler.

Character Streams

This classification of the stream is again based on the type of files. These streams allow character by character reading and writing of data instead of the traditional Unicode conventions. There are many classes of this stream. Some of them are listed below.

  • FileReader
  • BufferReader
  • Reader
  • Writer
  • PrintWriter
  • InputStreamReader
  • OutputStreamReader
     

Also see,  Swap Function in Java

Frequently Asked Questions

What do you mean by I/O in Java?

I/O in Java refers to Input/Output operations that handle reading data from and writing data to various sources, like files and network connections.

Is I/O a package in Java?

Yes, I/O is part of the Java standard library, primarily implemented in the java.io package, which contains classes for handling input and output operations.

When to use Java I/O?

Use Java I/O when you need to read from or write to files, handle data streams, or perform network communication in your applications.

How to handle I/O errors in Java?

Handle I/O errors in Java using try-catch blocks to catch exceptions like IOException, ensuring graceful error handling and resource management.

What are the two streams of Java I/O?

The two main streams of Java I/O are Input Streams for reading data and Output Streams for writing data to various sources.

Conclusion

In this article, we have extensively discussed Input/Output Operations in Java. To enhance your skills, you can also read the blog Flow control in try-catch and finally blocks in Java and Include iostream on the Coding Ninjas Website.

We hope this blog has helped you enhance your knowledge regarding I/O Operations in Java. If you want to learn more, check out our Android Development Course on the Code360 Website to learn everything you need to know about Android development

Live masterclass