Adam Bien's Weblog

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!


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

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 #

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