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

In the previous post, we have discussed how to read the contents of a text file using a FileReader in Java. Since FileReader is meant for reading streams of characters, FileInputStream can be used for reading streams of raw bytes such as image data. There are several ways to read the contents of a file using FileInputStream:

1. FileInputStream’s read() method

FileInputStream’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 FileInputStream’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’s constructor, as shown below:

Download Code

 
In case the file is too large to read in a single read operation, we can use another overloaded version of the FileInputStream’s read() method, which can repeatedly read the specified number of bytes into a buffer until the end of file has been reached. This is demonstrated below:

Download Code

2. BufferedReader’s readLine() method

Another solution is to use the BufferedReader with InputStreamReader. The following code read streams of raw bytes using FileInputStream and decodes them into characters using a specified charset using an InputStreamReader, and construct the 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. Using Apache Commons IO

Another elegant solution is to use the IOUtils class from Apache Commons IO library whose toString() method can accept a FileInputStream and renders its contents as a string using specified charset, as shown below:

Download Code

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

 
Read More:

Read all text from a file into a String in Java