Whole text file to a String in Java
Java 11 adds support for this use-case with Files.readString, sample code:
Files.readString(Path.of("/your/directory/path/file.txt"));
Before Java 11, 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
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.