Last Updated: November 21, 2017
· fuadsaud

Single line read text file with Java


String fileContents = new Scanner(new File("path/to/file")).useDelimiter("\\Z").next()

The real deal

The Java IO API is very nice, allowing us to read tons of different streams in different ways, with it's generic interfaces and decorators.

But sometimes you just want to do simple things, and these nice patterns stand there just to clutter your code. Take as example the effort for reading a simple text file:

String line = "", fileContents = "";
StringBuffer buffer = new StringBuffer();

 try {
     BufferedReader br = new BufferedReader(new FileReader("/path/to/file"));
     while ((line = br.readLine()) != null) {
 } catch (IOException e) {
     System.err.println("Error: " + e);

 fileContents = buffer.toString();


and all done?

There is better a way. And best: it's right there in the Java STD API: a fancy class called Scanner, that abstracts some ugly parts of reading streams. It's constructor takes any input source (like an InputStream or File), allowing you to wrap any kind of stream you usually deal with.

Scanner makes life easier to read the streams in tokens (useful for CSV-like files), and it even provide conveniences like converting data to integer when reading from stream.
By default, the token delimiter used by scanner is the '\n' (line feed), but you can define any character you want. The next() method allows you to retrieve the next token, based on this delimiter. But what if you set the delimiter to EOF? This nasty trick works, and it's pretty simple:

String fileContents = new Scanner(new File("path/to/file")).useDelimiter("\\Z").next()

The "\Z" here does the trick. Since the tokens end at EOF, a single call to next will bring you the whole content of the file.

Check out the docs for more convenience methods: