lyalwg
Last Updated: November 21, 2017
·
8.385K
· fuadsaud

Single line read text file with Java

tl;dr

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) {
         fileContents.append(thisLine);
      } 
 } catch (IOException e) {
     System.err.println("Error: " + e);
 }

 fileContents = buffer.toString();

yes

File.read('/path/to/file')

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.
2
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:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html