需要帮助使此代码更有效

时间:2010-12-24 17:37:45

标签: java nio

我总是使用此方法轻松读取文件的内容。它足够有效吗? 1024是否适合缓冲区大小?

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

3 个答案:

答案 0 :(得分:2)

尝试以下方法,它应该有效(好):

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

答案 1 :(得分:2)

我总是期待FileUtils http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html看看他们是否有方法。在这种情况下,我会使用readFileToString(文件) http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29

他们已经处理了几乎所有的问题......

答案 2 :(得分:2)

您可能会发现这很快。

String text = FileUtils.readFileToString(file);

AFAIK,它使用默认缓冲区大小8K。但是我发现像64K这样的较大尺寸可以略有不同。

相关问题