This post will discuss how to read the contents of a file using an InputStream in Java.

InputStream abstract class is the super class of all classes representing an input stream of bytes. There are several ways to read the contents of a file using InputStream in Java:

1. Using Apache Commons IO

An elegant and concise solution is to use the IOUtils class from Apache Commons IO library whose toString() method accepts an InputStream and renders its contents as a string using specified encoding, as shown below:

Download Code

2. BufferedReader’s readLine() method

Another solution is to use the BufferedReader. The following code read streams of raw bytes using InputStream and decodes them into characters using a specified charset using an InputStreamReader, and form a string using a platform-dependent line separator. Here, each invocation of the readLine() method would read bytes from the file and convert them into characters.

Download Code

3. InputStream’s read() method

InputStream’s read() method reads a byte of data from the input stream. It returns the next byte of data, or -1 if the end of the file is reached, and throws an IOException if an I/O error occurs.

Download Code

 
The InputStream’s read() method has an overloaded version that can read specified length bytes of data from the input stream into an array of bytes. We can use this method to read the whole file into a byte array at once. The corresponding bytes then can be decoded into characters with the specified charset using the String constructor.

Download Code

 
In case the file is too large to read in a single read operation, we can open an input stream of bytes using InputStream and repeatedly read bytes of data from it into a byte array using another overloaded method read(byte[], int, int) until the end of file has been reached. Finally, to get output in the string format, pass the byte array to the String constructor with a charset for decoding. This is demonstrated below:

Download Code

That’s all about reading a file using InputStream in Java.

 
Read More:

Read all text from a file into a String in Java