×

Search anything:

Different ways to handle Input and Output in Java

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 45 minutes | Coding time: 30 minutes

Java is one of the most widely used languages which work on all platforms. It follows object-oriented programming concepts. There are many features provided in Java but we are only explaining different types of input and output streams which is used in Java.

In short, the different ways of taking input and output in Java are:

  • Input Streams in Java
    • FileInputStream
    • ObjectInputStream
    • SequenceInputStream
    • ByteArrayInputStream
    • StringBufferInputStream
  • Output Streams in Java
    • BufferedOutputStream
    • DataOutputStream
    • PrintStream
    • ObjectOutputStream
    • FileOutputStream

Each stream specializes in a specific application and we have covered it in respective sections over this article at OpenGenus. Go through this article carefully and follow along the code examples to understand this deeply.

Introduction

Input and Output are two essential components of any programming language. In every language, input provides data to the program or the code written and output gives the result using memory and input data.

These two streams are explicitly used in file operation using java.io package. According to JDK 8, 12 interface and 51 classes provide standard input and output streams. This helps the users to interact with the program explicitly. By the word "standard input", we mean that the input is taken from the keyboard and by "standard output", the result computed by the input data is displayed on the screen. These are part of the class stream package.

Basic Input/ Output classes

There are many classes like reader-writer, InputStream and OutputStream, random access file. These classes are abstract based classes for basic input-output file operations. These base classes have separate constructors and when we define their class file we need an absolute path. The file class directly interacts with creating a file, determining the length of the file in bytes, remaining files or deleting a file using file objects. There are many methods of this file class and none of them deal with read or write operations or how the data is retrieved or stored in the file. For that, we have FileInputStream and FileOutputStream.

InputStream

This is an abstract class for streaming bytes in input. In the case of the byte stream, the data is transferred as it is in the computer memory. No transformation takes place. It has many classes, some of them are named and defined below -

  1. FileInputStream
  2. ObjectInputStream
  3. SequenceInputStream
  4. ByteArrayInputStream
  5. StringBufferInputStream

Most of the methods of this stream throw IOException.

FileInputStream

FileInputStream is used for reading bytes from the file through the defined functions of this class. There are 3 constructors of FileInputStream for creating an object and connecting it to the file, by using a file descriptive object that represents an existing connection to the file and also to connect the file by using name respectively. These are the function of the 3 constructors. The methods defined under this class are used to read bytes of the file or to close the stream and release the sources associated with it. These constructors and methods mainly produce 3 types of Exceptions namely IOException, NullPointerException, FileNotFoundException.
Important points about FileInputStream −

  • This class is meant for reading streams of raw bytes such as image data.
  • For reading streams of characters, use FileReader.

Syntax for Java.io.FileInputStream class −

InputStream instream = new FileInputStream (“file.txt”);
instream.read()

Code for FileInputStream

import java.io.*;
import java.io.FileInputStream;

class FileInStream3 {
    public static void main (String args[])
        throws IOException, FileNotFoundException 
        //The file is the file of this program
        {
            InputStream instream = new FileInputStream (“FileInStream3.java”);

            int Size = instream.available();
            System.out.println(“Size = “ + Size);
            System.out.println(“Skip 12 then read 25 characters.”);
            instream.skip(12);

            for (int i = 0; i <=25; i++)
                System.out.println((char)instream.read());
                System.out.println();
                instream.close();
        }
}

Output

Size = 566
Skip 12 then read 25 characters.
Illustrate FileInputStream

ObjectInputStream

ObjectInputStream supports reading of an individual object field. It is a subclass of the object and it returns the individual object field to the subpackage of ObjectInputStream and its subclass as well as inner class is known as ObjectInputStream.GetFeild.

Important point about ObjectInputStream are follows-

  • It is used for the rcovery of the object that were previously serialized.It guarantees that the type of all items in the graph made from the stream coordinate the classes present in the Java Virtual Machine.
  • Standard mechanism is used to load the class as per requirement.

Syntax for Java.io.SequenceInputStream class is -

FileInputStream is = new FileInputStream("EmployeeObject.ser");
ObjectInputStream ObjectIn = new ObjectInputStream(is);
ObjectIn.readObject();

Code for ObjectInputStream

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamDemo {

	public static void main(String[] args) {
		try {
			FileInputStream is = new FileInputStream("EmployeeObject.ser");
			ObjectInputStream ObjectIn = new ObjectInputStream(is);
			Employee emp = (Employee) ObjectIn.readObject();
			ObjectIn.close();
			is.close();
			System.out.println(emp.toString());
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
	}
}

Output

Employee:: Name=Coder Age=18 Gender=Male Role=Student 

SequenceInputStream

SequenceInputStream class allows a combination of multiple streams into a single stream. It is used for read and write operations in a file at the same time through a single file object.This class logically concatenates other input streams. It starts with the collection of input streams and reads it until the end of the file is reached.

Syntax for Java.io.SequenceInputStream class is -

SequenceInputStream SequenceIn = new SequenceInputStream(enumeration); 

Code for SequenceInputStream:

import java.io.*; 
import java.util.*; 
  
class SequenceISDemp 
{ 
    public static void main(String args[])throws IOException 
    { 
  
        //creating the FileInputStream objects for all the following files 
        FileInputStream file1=new FileInputStream("file1.txt"); 
        FileInputStream file2=new FileInputStream("file2.txt"); 
        FileInputStream file3=new FileInputStream("file3.txt"); 
  
        //adding fileinputstream obj to a vector object 
        Vector v = new Vector(); 
          
        v.add(file1); 
        v.add(file2); 
        v.add(file3); 
          
        //creating enumeration object by calling the elements method 
        Enumeration enumeration = v.elements(); 
  
        //passing the enumeration object in the constructor 
        SequenceInputStream SequenceIn = new SequenceInputStream(enumeration); 
          
        // determine how many bytes are available in the first stream 
        System.out.println("" + SequenceIn.available()); 
          
        // Estimating the number of bytes that can be read  
        // from the current underlying input stream  
        System.out.println( SequenceIn.available()); 
          
        int i = 0; 
        while((i = SequenceIn.read())! = -1) 
        { 
            System.out.print((char)i); 
        } 
        SequenceIn.close(); 
        file1.close(); 
        file2.close(); 
        file3.close(); 
    } 
} 

Output

19
This is first file This is second file This is third file

ByteArrayInputStream

ByteArrayInputStream is used to read an array of byte data. It is using the memory that is an array of bytes as a source. There are 2 constructors -> first constructor is used for taking the entire byte array as the source whereas the second constructor takes the part of an array starting from start index and length ‘l’ bytes as the source. These two constructors are invoked after the declaration of the file object.

Syntax for java.io.ByteArrayInputStream class −

ByteArrayInputStream bin1 = new ByteArrayInputStream(bArray);

The fields for java.io.ByteArrayInputStream class −

  • protected byte[] buf − This is an array of bytes that was provided by the creator of the stream.
  • protected int count − This is the index one greater than the last valid character in the input stream buffer.
  • protected int mark − This is the currently marked position in the stream.
  • protected int pos − This is the index of the next character to read from the input stream buffer.

Code for ByteArrayInputStream

import java.io.*;
class BAInStream2 {
public static void main(String args[])
throws IOException {

string str = "Java is an object oriented language.";
byte [] bArray = str.getBytes();

ByteArrayInputStream bin1 = new ByteArrayInputStream(bArray);

ByteArrayInputStream bin2 = new ByteArrayInputStream(bArray,0,26);
for (int k=0; k<bArray.length; k++)
{
int ch;
ch = bin1.read();
System.out.println((char) ch);
}
System.out.println();

for (int j=0; j<26; j++)
{
int kh;
kh = bin2.read();
System.out.print((char) kh); }

System.out.println();
}}

Output

Java is an object oriented language.
java is an object oriented

StringBufferInputStream

StringBufferInputStream is similar to ByteArrayInputStream. It takes an argument in the form of string byte data and operations of these bytes are similar as of string operations.Applications can also read bytes from a byte array by using a ByteArrayInputStream.Only the low eight bits of each character in the string are used by this class.

Syntax for Java.io.SequenceInputStream class is -

StringBufferInputStream fileIN = new StringBufferInputStream(comments);
DataInputStream dis = new DataInputStream(fileIn);

The fields for Java.io.StringBufferInputStream class −

  • protected String buffer − This is the string from which bytes are read.
  • protected int count − This is the number of valid characters in the input stream buffer.
  • protected int pos − This is the index of the next character to read from the input stream buffer.

Code for StringBufferInputStream

import java.io.*;
public class StringIn
{
  public static void main(String args[]) throws IOException
  {
    String comments = "Java\nis\na\npurely\nobject\noriented\nlanguage";
    StringBufferInputStream fileIN = new StringBufferInputStream(comments);
    DataInputStream dis = new DataInputStream(fileIn);

    String str;
    while( ( str = dis.readLine() ) != null )
    {
      System.out.println(str);
    }
    dis.close();   fileIn.close();
  }
}

Output

Java
is 
a
purely
object
oriented
language

OutputStream

It is an abstract class for byte stream output. The class object is used to accept bytes and send them to their specific destination or in other words writing bytes into file. The class has only one default constructor which means we can only initialize the file variable to its null value. It has many classes, some of them are named and defined below -

  1. BufferedOutputStream
  2. DataOutputStream
  3. PrintStream
  4. ObjectOutputStream
  5. FileOutputStream

BufferedOutputStream

BufferedOutputStream supports buffered output which means it takes data from the buffer memory and output file object is used to retrieve data from the buffered memory. With the help of this class we can setup an output stream which can write bytes to the input without making a call to the system for each byte.

Syntax for Java.io.BufferedOutputStream class −

bw = new  BufferedWriter(fw);
bw.write(str);

The fields for Java.io.BufferedOutputStream class −

  • protected byte[] buf − This buffer stores the data.
  • protected int count − This is the number of valid bytes in the buffer.
  • protected OutputStream out − This is the underlying output stream to be filtered.

Code for BufferedOutputStream

import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
public class WriterDemo {

public static void main(String args[]) throws FileNotFoundException, IOException {
    BufferedWriter bw = null;
    Sting str = "Learning Java Language is really intresting";

    File file = new File("C:/myfile.txt");
    if(!file.exists()){
        file.createNewFile();
    }
    FileWriter fw = new FileWriter(file);
    bw = new  BufferedWriter(fw);
    bw.write(str);
    System.out.println("File is written sucessfully");

    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    int ch = br.read();

    while((char = br.read())!=-1)

    System.out.println((char) ch);
    }
}

Output

File is written sucessfully

DataOutputStream

DataOutputStream supports primitive data type example int, float, char, and boolean from and to file, respectively. There is a class DataOutputStream that enables us to write primitive Java data types to OutputStream. Later, an application can use it to read the data back.

Syntax for Java.io.DataOutputStream class −

File file = new File("Data");
FileOutputStream fileOut = new FileOutputStream(file);
DataOutputStream dout = new DataOutputStream(fileOut);

The fields for Java.io.DataOutputStream class −

  • protected int written − This is the number of bytes written to the data output stream so far.
  • protected OutputStream out − This is the underlying output stream to be filtered.

Code for DataOutputStream

import java.io.*;
class DataOutIn {
    public static void main (String args[])
    throws IOException {
        File file = new File("Data");
        FileOutputStream fileOut = new FileOutputStream(file);
        DataOutputStream dout = new DataOutputStream(fileOut);

        dout.writeInt(120);
        dout.writeDouble(3.14159);
        dout.writeChar('B');
        dout.writeBoolean(true);
        dout.close(); // closes DataOutputStream

        fileOut.close(); //closes FileOutputStream

        FileInputStream fileIn = new FileInputStream(file);
        DataInputStream din = new DataInputStream(fileIn);

        System.out.println(din.readInt());
        System.out.println(din.readDouble());
        System.out.println(din.readChar());
        System.out.println(din.readBoolean());

        din.close();
        fileIn.close();
    }
}

Output

120
3.14159
B
True

PrintStream

PrintStream supports writing to console System.out. It is an instance of the subclass of OutputStream. "println" is a function that is used to print literals. "println" is one of the functions of the subclass. This class adds functionality to another output stream.

Syntax for Java.io.PrintStream class:

FileOutputStream fileOut=new FileOutputStream("file.txt"); 
PrintStream PrintOut=new PrintStream(fileOut); 

The fields for Java.io.PrintStream class −

  • protected OutputStream out − This is the output stream to be filtered.

Code for PrintStream

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.PrintStream; 
import java.util.Locale; 

class Printstream 
{ 
    public static void main(String args[]) throws FileNotFoundException 
    { 
        FileOutputStream fileOut=new FileOutputStream("file.txt"); 
          
        //creating Printstream obj 
        PrintStream PrintOut=new PrintStream(fileOut); 
        String s="First"; 
  
        //writing to file.txt 
        char c[]={'J','A','V','A'}; 
          
        //illustrating print(boolean b) method 
        PrintOut.print(true); 
          
        //illustrating print(int i) method 
        PrintOut.print(1); 
          
        //illustrating print(float f) method 
        PrintOut.print(52.692f); 
          
        //illustrating print(String s) method 
        PrintOut.print("Object-Oriented language."); 
        out.println(); 
          
        //illustrating print(Object Obj) method 
        PrintOut.print(fout); 
        PrintOut.println(); 
          
        //illustrating append(CharSequence csq) method 
        PrintOut.append("Java"); 
        PrintOut.println(); 
          
        //illustrating checkError() method 
        PrintOut.println(out.checkError()); 
          
        //illustrating format() method 
        PrintOut.format(Locale.UK, "Welcome to Java %s language.", s); 
          
        //illustrating flush method 
        PrintOut.flush(); 
          
        //illustrating close method 
        PrintOut.close(); 
    } 
} 

Output

true152.692Object-Oriented language.
java.io.FileOutputStream@1540e19dJava
false
Welcome to Java language

ObjectOutputStream

ObjectOutputStream supports the output of a class object to a file. It is used for supporting access to individual object fields by using the inner class of object output stream called ObjectOutputStream.PutFeild. It provides acccess to the fields that are to be written to ObjectOutput.

Syntax for Java.io.ObjectOutputStream.PutField class −

FileOutputStream fileout = new FileOutputStream("file.txt"); 
ObjectOutputStreamDemo ObjectOut = new ObjectOutputStreamDemo(fileout); 

Code for ObjectOutputStream

import java.io.*; 
class ObjectOutputStreamDemo extends ObjectOutputStream 
{ 
    public ObjectOutputStreamDemo(OutputStream out) throws IOException 
    { 
        super(out); 
    } 
      
    public static void main(String[] args) throws IOException, 
    ClassNotFoundException  
    { 
        FileOutputStream fileout = new FileOutputStream("file.txt"); 
        ObjectOutputStreamDemo ObjectOut = new ObjectOutputStreamDemo(fileout); 
        Character c = 'A'; 
          
        //illustrating annotateClass(Class<?> cl) method 
        ObjectOut.annotateClass(Character.class); 
          
        //Write the specified object to the ObjectOutputStream 
        ObjectOut.writeObject(c); 
          
        //flushing the stream 
        ObjectOut.flush(); 
          
        //closing the stream 
        ObjectOut.close(); 
          
        FileInputStream fileIn = new FileInputStream("file.txt"); 
        ObjectInputStream ObjectIn = new ObjectInputStream(fileIn); 
        System.out.print(ObjectIn.readObject()); 
        ObjectIn.close(); 
    } 
} 

Output

A

FileOutputStream

It is used to write bytes to the file through the defined functions of this class. The constructors of this class are used to define an object to write to the specific file or to establish a connection to the specific file. There are many defined methods used for the manipulation of the file.
The output operation includes the closing of a file, returning the unique channel of a file and setting an offset of a file. The constructor of this stream throw "FileNotFoundException" and it throw "SecurityException" if the security manager denies access to write into a specific file.

Syntax for Java.io.FilterOutputStream class −

OutputStream fileOUT = new FileOutputStream (“myFile”);

The fields for Java.io.FilterOutputStream class −

  • protected OutputStream out − This is the output stream to be filtered.

Code for FileOutputStream

import java.io.*;
class FileOutIn {
    public static void main (String arg[])
        throws FileNotFoundException, IOException {
            String str = "Java is a purely object oriented language. ";
            byte [] bstr = str.getBytes();
            OutputStream fileOUT = new FileOutputStream (“myFile”);
            for (int k =0; k<bstr.length; k++)
                fileOUT.write (bstr [k]);
                fileOUT.close(); // closes output stream

            InputStream fileIn = new FileInputStream(“myFile”);
            System.out.println(“Contents of myFile are:”);

            //read and display file contents
            for (int i=0; i<=bstr.length; i++)
                System.out.println((char) fileIn.read());
                System.out.println();
                fileIn.close(); //closes input stream
        }
}

Output

Contents of myFile are :
Java is a purely object oriented language.

With this, you will have a complete idea of handling input and output in Java. Enjoy.

Different ways to handle Input and Output in Java
Share this