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..
Java 7 improves on this sorry state of affairs with the
Files
class (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:Or into one String:
If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?
In Java 8 (no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.
AFAIK, there is no one-liner with standard libraries. Typical approach with standard libraries would be something like this:
Notes:
Not within the main Java libraries, but you can use Guava:
Or to read lines:
Of course I'm sure there are other 3rd party libraries which would make it similarly easy - I'm just most familiar with Guava.
No external libraries needed. The content of the file will be buffered before converting to string.
No external libraries needed. The content of the file will be buffered before converting to string.