Reading A File Into A String - With JDK 1.7


import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileReader {

    public static void main(String[] args) throws IOException {
        Path file = Paths.get("./readme.txt");
        BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
        StringBuilder content = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            content.append(line).append("/n");
        }
        System.out.println("Content: " + content.toString());
    }
}

NetBeans 7.0.1 not only runs and uses JDK 1.7 - it also provides hints and refactorings to transform your legacy JDK 1.6 code into JDK 1.7 :-).


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Where is the benefit regarding the try catch when the method throws the IOException anyway?

Posted by martin on August 08, 2011 at 12:54 PM CEST #

@Martin,

there is no catch! :-)

http://blogs.oracle.com/arungupta/entry/totd_167_automatic_resource_management

Search for Automatic Resource Management (ARM),

thanks!,

adam

Posted by Adam Bien on August 08, 2011 at 01:09 PM CEST #

Would have been nice in 1999. Now it's... too little, way way too late

Posted by Christian on August 08, 2011 at 01:24 PM CEST #

Is there also a performance difference between the NIO and plain old InputStream ?
I read it more utilizes the underlying OS-dependent file access?

Posted by Matthias on August 08, 2011 at 03:08 PM CEST #

But there is a catch where the "read()" method is called. And this is the same with or without the try statement of JDK7.

Posted by martin on August 08, 2011 at 03:42 PM CEST #

Ok, after reading the link i actually understand your code sample =). The main intention is not lieing on the try catch but on the automatic resource handling. nice.

Posted by martin on August 08, 2011 at 03:48 PM CEST #

Martin's question was (probably) on "throws IOException" part. Is it necessary, or even valid at all?

Or perhaps IOException falls through ARM, freeing "reader" on its way and is propagated to the caller?

Posted by Pyth0n on August 08, 2011 at 05:19 PM CEST #

If we want our method to throw a specific exception instead of such a generic IOException, it's still better to put a catch there.

Posted by Sérgio on August 08, 2011 at 05:50 PM CEST #

Or you can use Files.readAllLines() and skip the BufferedReader altogether.

Posted by Michael on August 08, 2011 at 07:31 PM CEST #

@Martin the benefit is that there is no memory leak :)

Posted by mbien on August 08, 2011 at 08:06 PM CEST #

new Scanner(file).useDelimiter("\\Z").next(); anyone?

Posted by Paulo Silveira on September 09, 2011 at 07:32 AM CEST #

@Paulo
Nice!

Posted by 88.149.245.206 on September 20, 2011 at 02:56 AM CEST #

new line is \n not /n

Posted by ofir on August 06, 2013 at 08:55 PM CEST #

How about a one liner with Commons IO:

String str =
FileUtils.readFileToString(path.toFile, StandardCharsets.UTF_8);

Posted by Nestor Hernandez on March 08, 2014 at 05:12 AM CET #

Resource resource = context.getResource("classpath:" + filename);
Files
.lines(Paths.get(resource.getURI()), Charset.forName("UTF-8"))
.filter(line -> line != null && !line.isEmpty())
.forEach(line -> System.out.println(line));

Posted by Max on August 26, 2014 at 08:33 AM CEST #

How about this?
String s = new String(Files.readAllBytes(path))

Posted by Oliver Doepner on September 15, 2014 at 01:21 AM CEST #

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