Skip to content

Instantly share code, notes, and snippets.

@rupertbates
Created May 2, 2013 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rupertbates/5503043 to your computer and use it in GitHub Desktop.
Save rupertbates/5503043 to your computer and use it in GitHub Desktop.
Read text from a file using a FileChannel and MappedByteBuffer
public static String fastReadTextFromFile(File file) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
FileChannel ch = inputStream.getChannel();
MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY,
0L, ch.size());
byte[] barray = new byte[Math.min(mb.remaining(), BYTE_ARRAY_SIZE)];
int getSize;
StringBuilder sb = new StringBuilder();
while (mb.hasRemaining()) {
getSize = Math.min(mb.remaining(), BYTE_ARRAY_SIZE);
mb.get(barray, 0, getSize);
sb.append(new String(barray));
}
return sb.toString();
} catch (FileNotFoundException e) {
LogHelper.error("Error in readTextFromFile for file " + file.getPath(), e);
} catch (IOException e) {
LogHelper.error("Error in readTextFromFile for file " + file.getPath(), e);
} finally {
try {
if (inputStream != null) {
LogHelper.verbose("closing inputStream in fastReadTextFromFile");
inputStream.close();
}
} catch (IOException e) {
LogHelper.error("Error trying to close inputStream in fastReadTextFromFile for file " + file.getPath(), e);
}
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment