gpt4 book ai didi

java - BufferedInputStream 与 ByteArrayInputStream

转载 作者:搜寻专家 更新时间:2023-10-31 20:28:54 25 4
gpt4 key购买 nike

以下是在处理文件之前将整个文件读入内存的三种方法:

方法一:

fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

方法 B:

ByteArrayInputStream bi =
new ByteArrayInputStream(
org.apache.commons.io.FileUtils.readFileToByteArray(file))

方法 C:

File file = new File(yourFileName);
RandomAccessFile ra = new RandomAccessFile(yourFileName, "rw"):
byte[] b = new byte[(int)file.length()];
try {
ra.read(b);
} catch (Exception e) {
e.printStackTrace();
}

为什么我更喜欢一种方法而不是另一种方法?
是否有任何特定的用例要求一种方法优于另一种方法?
为什么不改用固定长度的 byte[]

最佳答案

除非您需要任何特殊的功能(例如随机访问),否则包装到 BufferedInputStream 中的 InputStream 是从提供流式传输功能的任何类型的数据源中顺序读取的通用选择。

这将提供合理的性能(通过缓冲),代码是通用的,因为它可以处理任何流,而且非常重要 - 可处理流的大小不受可用堆内存的限制。

因此,除非您有非常令人信服的理由针对特殊情况 API 进行编码,否则请使用标准 InputStream 并根据需要对其进行包装。


编辑:回应@IUnknown 在评论中提出的问题:

  1. What is the approach in the case of a random access - I thought BufferedInputStream is the preferred solution even in that case?

没有用于随机访问的通用接口(interface)。你想错了。您至少可以如此礼貌地研究基础知识的基础知识:http://docs.oracle.com/javase/tutorial/essential/io/

  1. the size of processable streams isn't limited by the available heap memory - the buffer must be having a limit.Are you saying that the internal array automatically re-sizes if its filled up while reading?

同样,这已包含在基础知识中(见上文)。使用 ByteArrayInputStream 你需要一个 byte[] 来保存整个流。那怎么受内存限制? (更糟糕的是,它也受到最大数组大小的限制)。

  1. Is there any difference in the buffer behavior between a Buffered stream and a ByteArray stream - I thought they are backed up by similar buffer behaviour

我不知道该说什么。你想错了。撇开基本事实不谈,它们都扩展了 InputStream 并以某种方式在内部使用字节数组(从技术上讲,两者都可以在不使用任何数组的情况下实现,这是最自然的实现方式)。他们没有共同点。 BufferedStream 包含另一个 流的一小部分动态。 ByteArrayInputStream 在 2.

建议:这里的人们很乐意就使用哪种工具来完成哪些工作向您提供建议。但不要指望被喂食。显示一些 努力,stackoverflow 不是辅导网站。停止“思考”并开始“学习”- 教程就在那里,并且自语言诞生以来就一直存在。

关于java - BufferedInputStream 与 ByteArrayInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18291074/

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