How to get file content in java?

commons-io has:

IOUtils.toString(new FileReader("file.txt"), "utf-8");

With Java 7 there is an API along those lines.

Files.readAllLines(Path path, Charset cs)


Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();

Tags:

Java

Java Io