Read entire file using Scanner

Most programming contest problems have you reading a file for input. And while there are several ways to read files in Java, I’ve found that most students find the Scanner class the easiest to work with.

We usually use the hasNext and next set of methods, along with their buddies nextInt, nextDouble and nextLine when going through a file. But sometimes it’s easier to pull the entire contents into a single string. And we do that with the useDelimiter method.

useDelimiter takes a regular expression that tells the Scanner what to split on when you use the next method. Normally next breaks tokens on any whitespace. For this we’re going to change the delimiter to \Z which is the regular expression token for the end of the file. Remember that when you’re using regular expressions in Java you have to escape the backslash, so you wind up \\Z as the delimiter.

String contents = new Scanner(new File("some.dat")).useDelimiter("\\Z").next();

Now contents contains the entire contents of the file some.dat. And, it’s still got the line breaks so you can use those to split into an array if you need to go that route. Newsletter

Want to stay in touch and keep up to date with the latest posts @

Leave a Reply

Your email address will not be published. Required fields are marked *