What is simplest way to read a file into String? [duplicate]

I am trying to read a simple text file into a String. Of course there is the usual way of getting the input stream and iterating with readLine() and reading contents into String.

Having done this hundreds of times in past, I just wondered how can I do this in minimum lines of code? Isn't there something in java like String fileContents = XXX.readFile(myFile/*File*/) .. rather anything that looks as simple as this?

I know there are libraries like Apache Commons IO which provide such simplifications or even I can write a simple Util class to do this. But all that I wonder is - this is a so frequent operation that everyone needs then why doesn't Java provide such simple function? Isn't there really a single method somewhere to read a file into string with some default or specified encoding?


Solution 1:

Yes, you can do this in one line (though for robust IOException handling you wouldn't want to).

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

There is a constructor that takes a File and a String charSetName (among many other overloads). These two constructor may throw FileNotFoundException, but like all Scanner methods, no IOException can be thrown beyond these constructors.

You can query the Scanner itself through the ioException() method if an IOException occurred or not. You may also want to explicitly close() the Scanner after you read the content, so perhaps storing the Scanner reference in a local variable is best.

See also

  • Java Tutorials - I/O Essentials - Scanning and formatting

Related questions

  • Validating input using java.util.Scanner - has many examples of more typical usage

Third-party library options

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

Guava

com.google.common.io.Files contains many useful methods. The pertinent ones here are:

  • String toString(File, Charset)
    • Using the given character set, reads all characters from a file into a String
  • List<String> readLines(File, Charset)
    • ... reads all of the lines from a file into a List<String>, one entry per line

Apache Commons/IO

org.apache.commons.io.IOUtils also offer similar functionality:

  • String toString(InputStream, String encoding)
    • Using the specified character encoding, gets the contents of an InputStream as a String
  • List readLines(InputStream, String encoding)
    • ... as a (raw) List of String, one entry per line

Related questions

  • Most useful free third party Java libraries (deleted)?

Solution 2:

From Java 7 (API Description) onwards you can do:

new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

Where filePath is a String representing the file you want to load.

Solution 3:

You can use apache commons IO..

FileInputStream fisTargetFile = new FileInputStream(new File("test.txt"));

String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");