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: java
Posted in: Development, How to's, quick tips