Search code examples
javanio

Need help making this code more efficient


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();
}

Solution

  • You may find that this is fast enough.

    String text = FileUtils.readFileToString(file);
    

    AFAIK, this uses the default buffer size of 8K. However I have found larger sizes such as 64K can make a slight difference.