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?
Yes, you can do this in one line (though for robust
IOExceptionhandling you wouldn’t want to).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 tonext().There is a constructor that takes a
Fileand aString charSetName(among many other overloads). These two constructor may throwFileNotFoundException, but like allScannermethods, noIOExceptioncan be thrown beyond these constructors.You can query the
Scanneritself through theioException()method if anIOExceptionoccurred or not. You may also want to explicitlyclose()theScannerafter you read the content, so perhaps storing theScannerreference in a local variable is best.See also
Related questions
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.Filescontains many useful methods. The pertinent ones here are:String toString(File, Charset)StringList<String> readLines(File, Charset)List<String>, one entry per lineApache Commons/IO
org.apache.commons.io.IOUtilsalso offer similar functionality:String toString(InputStream, String encoding)InputStreamas aStringList readLines(InputStream, String encoding)ListofString, one entry per lineRelated questions
Most useful free third party Java libraries (deleted)?