Java 8: Reading A File Into A String


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

    public static void main(String[] args) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get("duke.java")));
    }

Enjoy Java 8!

Comments:

Can this be used to load project resources as well? I use getClass().getResource() for that, but then I still have to convert the resulting URL to a Path. A more elegant solution would be greatly appreciated!

Posted by Steven Van Impe on March 22, 2014 at 09:00 PM CET #

Constructing a String from byte[] without passing charset explicitly uses platform default encoding, thus is not portable. Please always specify encoding, e.g. using StandardCharsets from Java 7.

Posted by Tomasz N. on March 23, 2014 at 11:55 AM CET #

This actually works since Java 7

Posted by Rüdiger on March 23, 2014 at 06:52 PM CET #

I agree with Tomasz, reading file without specifying character encoding can work in test environment but could break in production, its very risky to be reliable.

Posted by Javin Paul on February 24, 2015 at 03:30 PM CET #

oh eh. nice Java 7 feature.

Posted by alex on March 19, 2015 at 12:16 PM CET #

try (BufferedReader reader =
Files.newBufferedReader(Paths.get("duke.java"))) {

//do manipulations

}

This way i will be able to use Lambda expressions and streams easily also.

Posted by Valleyman on August 10, 2015 at 06:42 PM CEST #

Slight suggestion - specify the charset when doing the conversion to String.

I've had issues with switching platforms and prefer to use UTF-8 explicitly -

String content = new String (Files.readAllBytes(file.toPath()),Charset.forName("UTF-8")); // if not specified, uses windows-1552 on that platform

Posted by John on October 02, 2015 at 10:59 PM CEST #

I agree with Tomasz, how to read fle without any specific character.

Posted by manchun on December 09, 2016 at 08:10 AM CET #

@manchun If you're sure your file hasn't any special character, use StandardCharsets.US_ASCII.

Posted by Yannick Majoros on July 11, 2017 at 10:03 AM CEST #

Nice way for reading a file - but when will Java really get user friendly to read a file? Why is it not possible to write:
Files.readFile("myFile.txt").

Posted by Frank on July 27, 2017 at 10:38 AM CEST #

Thank you! It was a great help. What I most loved about it was how you presented the information. Brilliant and helpful.

Posted by JAVA training in Indore on June 04, 2019 at 09:43 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License