28

以下两种缓冲方法之间有什么区别(如果有)?

Reader r1 = new BufferedReader(new InputStreamReader(in, "UTF-8"), bufferSize);
Reader r2 = new InputStreamReader(new BufferedInputStream(in, bufferSize), "UTF-8");
4

4 回答 4

32

r1效率更高。它InputStreamReader本身没有很大的缓冲区。BufferedReader可以设置为具有比 更大的缓冲区InputStreamReaderInputStreamReaderin将r2成为瓶颈。

简而言之:您应该通过漏斗而不是瓶子来读取数据。


更新:这是一个小基准程序,只需复制'n'粘贴'n'运行它。您无需准备文件。

package com.stackoverflow.q3459127;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class Test {

    public static void main(String... args) throws Exception {

        // Init.
        int bufferSize = 10240; // 10KB.
        int fileSize = 100 * 1024 * 1024; // 100MB.
        File file = new File("/temp.txt");

        // Create file (it's also a good JVM warmup).
        System.out.print("Creating file .. ");
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(file));
            for (int i = 0; i < fileSize; i++) {
                writer.write("0");
            }
            System.out.printf("finished, file size: %d MB.%n", file.length() / 1024 / 1024);
        } finally {
            if (writer != null) try { writer.close(); } catch (IOException ignore) {}
        }

        // Read through funnel.
        System.out.print("Reading through funnel .. ");
        Reader r1 = null;        
        try {
            r1 = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), bufferSize);
            long st = System.nanoTime();
            for (int data; (data = r1.read()) > -1;);
            long et = System.nanoTime();
            System.out.printf("finished in %d ms.%n", (et - st) / 1000000);
        } finally {
            if (r1 != null) try { r1.close(); } catch (IOException ignore) {}
        }

        // Read through bottle.
        System.out.print("Reading through bottle .. ");
        Reader r2 = null;        
        try {
            r2 = new InputStreamReader(new BufferedInputStream(new FileInputStream(file), bufferSize), "UTF-8");
            long st = System.nanoTime();
            for (int data; (data = r2.read()) > -1;);
            long et = System.nanoTime();
            System.out.printf("finished in %d ms.%n", (et - st) / 1000000);
        } finally {
            if (r2 != null) try { r2.close(); } catch (IOException ignore) {}
        }

        // Cleanup.
        if (!file.delete()) System.err.printf("Oops, failed to delete %s. Cleanup yourself.%n", file.getAbsolutePath());
    }

}

我的 Latitude E5500 与Seagate Momentus 7200.3硬盘的结果:

创建文件..完成,文件大小:99 MB。
通过漏斗阅读..在 1593 毫秒内完成。
通过瓶子阅读..在 7760 毫秒内完成。
于 2010-08-11T14:09:04.993 回答
5

r1BufferedReader当您将基于行的流作为支持readLine方法阅读时也更方便。您不必将内容逐个读入 char 数组缓冲区或字符。但是,您必须为变量显式r1转换为BufferedReader或使用该类型。

我经常使用这个代码片段:

BufferedReader br = ...
String line;
while((line=br.readLine())!=null) {
  //process line
}
于 2010-08-11T14:47:10.003 回答
2

针对上述评论中的罗斯·斯图特曼的问题(但也与 OP 相关):

BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputSream(inputStream), "UTF-8"));

BufferedInputStream是多余的(并且可能由于多余的复制而损害性能)。这是因为通过调用从大块中BufferedReader请求字符,而后者又(通过)调用从底层读取大块字节。InputStreamReaderInputStreamReader.read(char[], int, int)StreamDecoderInputStream.read(byte[], int, int)InputStream

您可以通过运行以下代码来说服自己:

new BufferedReader(new InputStreamReader(new ByteArrayInputStream("Hello world!".getBytes("UTF-8")) {

    @Override
    public synchronized int read() {
        System.err.println("ByteArrayInputStream.read()");
        return super.read();
    }

    @Override
    public synchronized int read(byte[] b, int off, int len) {
        System.err.println("ByteArrayInputStream.read(..., " + off + ", " + len + ')');
        return super.read(b, off, len);
    }

}, "UTF-8") {

    @Override
    public int read() throws IOException {
        System.err.println("InputStreamReader.read()");
        return super.read();
    }

    @Override
    public int read(char[] cbuf, int offset, int length) throws IOException {
        System.err.println("InputStreamReader.read(..., " + offset + ", " + length + ')');
        return super.read(cbuf, offset, length);
    }

}).read(); // read one character from the BufferedReader

您将看到以下输出:

InputStreamReader.read(..., 0, 8192)
ByteArrayInputStream.read(..., 0, 8192)

这表明BufferedReader请求来自 的大块字符InputStreamReader,而后者又从底层请求大块字节InputStream

于 2014-12-07T20:10:30.713 回答
1

FWIW,如果您在 Java 8 中打开文件,则可以使用Files.newBufferedReader(Path)。我不知道性能与此处描述的其他解决方案相比如何,但至少它推动了决定将什么构造缓冲到 JDK 中。

于 2015-10-02T19:16:28.200 回答