Implement how to load File as InputStream in Java
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:
- 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:
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:
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.
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.
The output of all the above programs is the same.