Created
May 2, 2013 15:33
-
-
Save rupertbates/5503043 to your computer and use it in GitHub Desktop.
Read text from a file using a FileChannel and MappedByteBuffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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