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..
解决方案
AFAIK, there is no one-liner with standard libraries.
Typical approach with standard libraries would be something like this:
public static String readStream(InputStream is) {
StringBuilder sb = new StringBuilder(512);
try {
Reader r = new InputStreamReader(is, "UTF-8");
int c = 0;
while ((c = r.read()) != -1) {
sb.append((char) c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
Notes:
in order to read text from file, use FileInputStream
if performance is important and you are reading large files, it would be advisable to wrap the stream in BufferedInputStream
the stream should be closed by the caller