简体   繁体   中英

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

Try the following, it should work (well):

public static String read(File file)
{
    StringBuilder str = new StringBuilder();

    BufferedReader in = null;

    String line = null;

    try
    {
        in = new BufferedReader(new FileReader(file));

        while ((line = in.readLine()) != null)
           str.append(line);

        in.close();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return str.toString();
}

I would always look to FileUtils http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html to see if they had a method. In this case I would use readFileToString(File) http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29

They have already dealt with almost all the problem cases...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM