Exercise:
Write a Java Program to read the content of a file line by line.
Click Here to View the Solution!
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class Main {
public static void main(String[] args) {
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");
// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);
// Reads first byte from file
int i = input .read();
while (i != -1) {
System.out.print((char) i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Click Here to View the Output!
First Line Second Line Third Line Fourth Line Fifth Line
Click Here to View the Explanation!
- This program performs the task of reading data from a given file by employing
BufferedInputStream()
method. - This method helps in speedy access of data, and reduces time consumption.
- First step of execution includes converting the contents of input file into
bytes
. - This
byte-stream
is then stored in aFileInputStream
type object. - Those converted bytes are then transformed into an array of bytes.
- For this purpose, a new object of
BufferedInputStream
is instantiated, which takes that file object as an argument to its constructor. - Initially, the first byte is read from the buffer, and is then stored into an
integer variable
. - The
while loop
reads each line from the file usingread()
method, and continues doing so till the value ofbyte
is not equal to-1
. - File is closed afterwards, also keep in mind, that file should be in the same location as the program.