Java – How to Read Whole Text File to a String

filefile-iojava

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data = System.IO.File.ReadAllText("path to file");

If not… what is the 'optimal way' to do this…?

Edit:

I prefer a way within Java standard libraries… I can not use 3rd party libraries..

Best Answer

apache commons-io has:

String str = FileUtils.readFileToString(file, "utf-8");

But there is no such utility in the standard java classes. If you (for some reason) don't want external libraries, you'd have to reimplement it. Here are some examples, and alternatively, you can see how it is implemented by commons-io or Guava.

Related Question