Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Implement how to load File as InputStream in Java

  • Last Updated : 21 Sep, 2021

Problem Statement: There is a file already existing in which the same file needs to be loaded using the InputStream method. 

Concept: While accessing a file either the file is being read or write. here are two streams namely fileInputStream and fileOutputStream 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Java Stream is the flow of data from source to destination. OutputStream and InputStream are abstractions over low-level access to data. InputStream is a source for reading data. A stream can have various kinds of sources, such as disk files, devices, other programs, and memory arrays. Several ways to read the contents of a file using InputStream in Java have been discussed below.

Suppose the text file is stored in path “/Users/mayanksolanki/Desktop/Folder/test.txt” and has content as below:



Approaches: 

  • Using Apache command IO libraries
  • Using readline() method of BufferedReaderClass
  • Using read() method of InputStreamClass

Let us describe and implement the methods one by one through examples:

Method 1: Using Apache Common IO library

The IOUtils class from Apache Commons IO library contains a toString() method that accepts an InputStream and renders its contents as a string as shown below:

Java




// Importing generic Classes/Files
import java.util.*;
 
// importing Apache specific Class/es
import org.apache.commons.io.IOUtils;
 
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating file object and specify file path
        File file = new file(
            "/Users/mayanksolanki/Desktop/Folder/test.txt");
        // create a stream to read contents of that file
 
        // Try block to check exception
        try {
 
            FileInputStream input
                = new FileInputStream(file);
            // Representing input object in form of string
 
            String contents = IOUtils.toString(input);
 
            // Print contents of that file
            System.out.println(contents);
        }
 
        // Catch block to handle exceptions
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 
Output: 



Method 2: BufferedReader’s readLine() method

Concept Used: Using inbuilt readLine() function : The readLine() method of BufferedReader class in Java is used to read one line text at a time. The end of a line is to be understood by ‘\r’ or ‘\n’ or EOF.

Here is the implementation of readLine() method: 

Java




// Importing generic Classes/Files
import java.io.*;
 
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create file object and specify file path
        File file = new File(
            "/Users/mayanksolanki/Desktop/Folder/test.txt");
 
        try (FileInputStream input
             = new FileInputStream(file)) {
            // create an empty string builder to store
            // string
 
            StringBuilder content = new StringBuilder();
            // create an object of bufferedReader to read
            // lines from file
 
            BufferedReader br = new BufferedReader(
                new InputStreamReader(input));
 
            String line;
            // store each line one by one until reach end of
            // file
 
            while ((line = br.readLine()) != null) {
                // append string builder with line and with
                // '/n' or '/r' or EOF
                content.append(line
                               + System.lineSeparator());
            }
 
            // print string builder object i.e content
            System.out.println(content.toString());
        }
 
        // Catch block to handle exceptions
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output: 

Method 3: InputStream’s read() method

The read() method of InputStream class, reads a byte of data from the input stream. The next byte of data is returned, or -1 if the end of the file is reached and throws an exception if an I/O error occurs. Refer to the program. 

Java




// Importing generic Classes/Files
import java.io.*;
 
class GFG {
 
    // Main driver function
    public static void main(String[] args)
    {
        // Creating file object and specifying path
        File file = new File(
            "/Users/mayanksolanki/Desktop/Folder/test.txt");
 
        try (FileInputStream input
             = new FileInputStream(file)) {
            int character;
            // read character by character
            // by default read() function return int between
            // 0 and 255.
 
            while ((character = input.read()) != -1) {
                System.out.print((char)character);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

There is another overloaded version of read() method that reads the specified length of bytes from the input stream into an array of bytes. The corresponding bytes can then be decoded into characters. Refer to the below example.

Java




import java.nio.charset.StandardCharsets;
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // create file object and specify path
        // specicified directory is random
        File file = new File(
            "/Users/mayanksolanki/Desktop/Folder/test.txt");
 
        // Try block to catch exception/s if any
        try {
            (FileInputStream input
             = new FileInputStream(file))
 
                // create a byte array of size equal to
                // length of file
                byte bytes[]
                = new byte[(int)file.length()];
 
            // read bytes from file
            input.read(bytes);
 
            // decode into string format
            String content
                = new String(bytes, StandardCharsets.UTF_8);
 
            // print contents of that file
            System.out.println(content);
        }
        catch (Exception e) {
 
            //
            e.printStackTrace();
        }
    }
}

Output 

The output of all the above programs is the same.
 

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!