gpt4 book ai didi

java - FileInputStream 是否没有缓冲以及为什么 BufferedInputStream 更快?

转载 作者:行者123 更新时间:2023-12-02 08:45:31 26 4
gpt4 key购买 nike

关于IO,我有两个问题。

A.在教程和一些 StackOverflow 答案中,他们声称 FileInputStream 没有缓冲。这是真的吗?

以下代码使用FileInputStream将数据读取到字节数组(1024字节)

class Test {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("./fos.txt");
FileOutputStream fos = new FileOutputStream("./copy.txt");

byte[] buffer = new byte[1024]; // Is this a buffer ?

int len;
while ((len = fis.read(buffer))!= -1) {
fos.write(buffer);
}

fos.close();
fis.close();
}
}

从 API 中,有一行:

public int read(byte b[]) throws IOException

  • @param b: the buffer into which the data is read.

B.如果都是缓冲的话,都是将数据放入缓冲区,并从缓冲区中取出数据,到底是哪里让BufferedInputStreamFileInputStream快呢?

谢谢

最佳答案

In a tutorial and some StackOverflow answers, they claimed that FileInputStream is not buffered. is that true ?

写入任何文件都会由操作系统缓冲,但是在这种情况下,Java 不会缓冲它。当您执行许多小写入时,缓冲会有所帮助,1 KB 的写入并不小。

The following code use FileInputStream to read data into a byte array(1024 bytes)

    int len;
while ((len = fis.read(buffer))!= -1) {
fos.write(buffer);
}

此循环已被破坏,因为它假设您始终读取恰好 1024 字节,并且文件长度始终为 1024 的倍数。

相反,您应该写出读取的长度。

    for (int len; (len = fis.read(buffer))!= -1; )
fos.write(buffer, 0, len);

If they are both buffered, they both put the data into the buffer, and fetch the data from the buffer, where exactly is the place that makes BufferedInputStream faster than FileInputStream?

在这种情况下,BufferedInputStream 将默认使用 8 KB 缓冲区。这会将系统调用的数量减少多达 8 倍,但是,在您的情况下,仅使用 8 KB byte[] 并保存一些冗余副本会简单得多。

public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream("./fos.txt");
FileOutputStream fos = new FileOutputStream("./copy.txt")) {

byte[] buffer = new byte[8 << 10]; // 8 KB
for (int len; (len = fis.read(buffer)) != -1; )
fos.write(buffer, 0, len);
}
}

关于java - FileInputStream 是否没有缓冲以及为什么 BufferedInputStream 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52640010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com