Read a File as String with Java

Thursday, June 16th, 2011

Introduction

I’m always Googling for a way to do this. This seems to be the best “idiomatic” solution I’ve found. So without further ado…

Example

public String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try{
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        return Charset.defaultCharset().decode(bb).toString();
    }
    finally {
        stream.close();
    }
}

You can leave a response, or trackback from your own site.

Tags:
Posted in: Development, How to's, quick tips



Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>