I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.
Is there a better/different way to read a file into a string in Java?
private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
.......
In one line (Java 8), assuming you have a Reader:
From this page a very lean solution:
or
If you want to set the charset
since java 7 you can do it this way.
Gathered all the possible ways to read the File as String from Disk or Network.
Guava: Google using classes
Resources
,Files
APACHE - COMMONS IO using classes IOUtils, FileUtils
Java 8 BufferReader using Stream API
Scanner Class with regex
\A
. which matches the beginning of input.Java 7 (
java.nio.file.Files.readAllBytes
)BufferedReader
usingInputStreamReader
.Example with main method to access the above methods.
@see
Java attempts to be extremely general and flexible in all it does. As a result, something which is relatively simple in a scripting language (your code would be replaced with "
open(file).read()
" in python) is a lot more complicated. There doesn't seem to be any shorter way of doing it, except using an external library (like Willi aus Rohr mentioned). Your options:Your best bet is probably the 2nd one, as it has the least dependencies.