Need help making this code more efficient
- by Rendicahya
I always use this method to easily read the content of a file. Is it efficient enough? Is 1024 good for the buffer size?
public static String read(File file) {
FileInputStream stream = null;
StringBuilder str = new StringBuilder();
try {
stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
}
FileChannel channel = stream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
while (channel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
str.append((char) buffer.get());
}
buffer.rewind();
}
} catch (IOException e) {
} finally {
try {
channel.close();
stream.close();
} catch (IOException e) {
}
}
return str.toString();
}