Need help making this code more efficient

Posted by Rendicahya on Stack Overflow See other posts from Stack Overflow or by Rendicahya
Published on 2010-12-24T17:37:44Z Indexed on 2010/12/24 17:54 UTC
Read the original article Hit count: 154

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about nio