I was solving problems at HackerRank to teach a friend how to code in Java and to process the input data it’s convenient to use Java’s built in Scanner
class.
However, in one of the problems we wanted to read a whole line at once and we noticed that the Scanner’s API is geared towards reading the next token, and it doesn’t have a method that reads the entire line. It has one method that skips a line and reads from the last point which is very weird to use, so we created a static method to just read the next entire line, keeping it simple.
public static String readLine(Scanner scanner) {
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
String r = scanner.next();
scanner.useDelimiter(oldDelimiter);
return r;
}
The Scanner
uses as its default token delimiter a whitespace
pattern, so what we do in this method is to temporarily replace the token delimiter for a newline
delimiter. Once set to newline
all we need to do is to read the next token, which will be the entirety of the line, and then we put the previous delimiter set back in place.
In Java 8 there’s a new Linebreak matcher expression \R
, however, if we want our method to be backwards compatible (as we don’t know on which JRE it could be running) we set the equivalent delimiter manually in our function
\R Any Unicode linebreak sequence, is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]
If you don’t like the static
function approach you can always repurpose this code and extend Scanner
into a custom MyScanner
class , and add a method nextLine
that does the same thing