Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Streams
2.1.
Input Streams
2.2.
Output Streams
2.3.
Byte Streams
2.4.
Character Streams
3.
Standard I/O Streams in Java
3.1.
Standard Input Stream (System.in)
3.2.
Standard Output Stream (System.out)
3.3.
Standard Error Stream (System.err)
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024

Introduction to Java I/O

Author Vasu Bansal
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

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.

Must Read, Multithreading in java, Duck Number 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 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");

            }
        }
       
    }
}

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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:

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");

            }
        }
       
    }
}

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:

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);
       
    }
}

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

Frequently Asked Questions

  1. Which stream class contains Java's print() and println() methods?
    Ans: The print() and println() methods are present in the PrintWriter stream class.
     
  2. What is the use of the DataInputStream in Java?
    Ans: It contains the methods for performing read operations in Java.
     
  3. How does the ByteStream process data in Java?
    Ans: The ByteStream processes byte by byte data, i.e. 8 bits at a time.

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 Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!

Next article
Reader Class in Java
Live masterclass