Java IO - Reading lines using BufferedReader and Scanner
Reading data from InputStream
If you use InputStream to read some data, and if you want to read characters until new line or ‘\n’.
You should use BufferedReader with FileInputStreamReader if your read from a file
BufferedReader reader = new BufferedReader(new FileInputStreamReader(pathToFile));
or with InputStreamReader if you read from any other InputStream
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Then read the lines like this:
String line;
while ((line = reader.readLine()) != null) {
// process line
}
You have to test the result of the readLine() method. It will return null when you get to the end of the stream. Use readLine() and stop when it returns null.
Don’t use readLine
while(reader.ready()) {
String line = reader.readLine();
}
because it will always return true and lead to an infinite loop.
The javadoc for the ready() method says:
Returns: True if the next read() is guaranteed not to block for input, false otherwise.
Since a readLine() at the end of stream position is guaranteed to return immediately, ready() must return true.
But if you really love InputStream then you can use a loop like this
InputStream stream;
char c;
String s = "";
do {
c = stream.read();
if (c == '\n')
break;
s += c + "";
} while (c != -1);
Use BufferedReader within the try-with block, which will close the resource after finishing with it.
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
// process line
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is possible to read the input stream with BufferedReader and with Scanner. If you don’t have a good reason, it is better to use BufferedReader
BufferedReader vs Scanner
Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing.
In fact you can pass a BufferedReader to a Scanner as the source of characters to parse.
The difference between BufferedReader and Scanner are following:
BufferedReaderis synchronized butScanneris not synchronized.BufferedReaderis thread-safe butScanneris not thread-safe.BufferedReaderhas larger buffer memory butScannerhas smaller buffer memory.BufferedReaderis faster butScanneris slower in execution.BufferedReaderreads data, butScannerparses data.- You can only read String using
BufferedReader, usingScanneryou can read to different data types like int. BufferedReaderis older thanScanner, it was added on JDK 1.1, whileScannerwas added on JDK 5 release.- The buffer size of
BufferedReaderis larger (8KB) as compared toScanner’s 1KB. BufferedReaderis more suitable for reading files with long String, whileScanneris more suitable for reading small user input from command prompt.BufferedReaderis synchronized, whileScanneris not, which means you cannot shareScanneramong multiple threads.BufferedReaderis faster thanScannerbecause it doesn’t spend time on parsing.BufferedReaderis a bit faster as compared toScanner.BufferedReaderis from java.io package, whileScanneris from java.util package.- Code to read a line from the console:
- BufferedReader
InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String st = br.readLine(); // You can make the object InputStreamReader object inside the BufferReader method. BufferReader br = new BufferedReader(InputStreamReader(System.in)); String st = br.readLine(); // You can even inspect the type of the input stream manually by using Parse method which accepts string parameter. int x = Integer.parseInt(br.readLine()); // Or you can pass the object directly. int x = Integer.parseInt(st); - Scanner
Scanner sc = new Scanner(System.in); String st = sc.nextLine();
- BufferedReader