Read all lines with BufferedReader
One line of code using Java 8:
line = buffer.lines().collect(Collectors.joining());
The idiomatic way to read all of the lines is while ((line = buffer.readLine()) != null)
. Also, I would suggest a try-with-resources
statement. Something like
try (InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream)) {
long length = 0;
String line;
while ((line = buffer.readLine()) != null) {
length += line.length();
}
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
If you want to end the loop when you receive an empty line, add a test for that in the while
loop
while ((line = buffer.readLine()) != null) {
if (line.isEmpty()) {
break;
}
length += line.length();
}
JLS-14.15. The break
Statement says
A
break
statement transfers control out of an enclosing statement.