Java中FileInputStream和BufferedInputStream有什么区别?

11

在Java中,FileInputStream和BufferedInputStream有何区别?


1
这个这个结合起来看,可以找到答案。 - Sotirios Delimanolis
3个回答

20

关键区别:

  • BufferedInputStream有缓冲区,但FileInputStream没有。

  • BufferedInputStream从另一个InputStream读取数据,而FileInputStream从文件中读取1

实际上,这意味着每次调用FileInputStream.read()会执行系统调用(开销很大)...而大多数调用BufferedInputStream.read()将从缓冲区返回数据。简而言之,如果进行“小”的读取,将BufferedInputStream放入流堆栈中将提高性能。

  • 对于大多数目的/用例,这就是所有相关的内容了。

  • 还有一些其他的东西(如标记/重置/跳过),但这些都是比较专业的...

  • 有关更详细的信息,请阅读Java文档...以及源代码。


1-或者更准确地说,从一些在操作系统的“文件系统”命名空间中具有名称的对象和操作系统允许您作为字节序列读取的对象中读取。这可能包括设备、命名管道和其他各种不被视为“文件”的东西。还值得注意的是,有一些类型的东西绝对不能使用FileInputStream读取。


7

你必须谷歌搜索或阅读Java文档

public class FileInputStream
extends InputStream

FileInputStream从文件系统中获取输入字节。可用的文件取决于主机环境。

FileInputStream用于读取原始字节流,例如图像数据。如果要读取字符流,请考虑使用FileReader。

更多详情请参考:https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html

public class BufferedInputStream
extends FilterInputStream

一个BufferedInputStream可以为另一个输入流添加功能,即缓冲输入并支持mark和reset方法。创建BufferedInputStream时,会创建一个内部缓冲区数组。从流中读取或跳过的字节,根据需要从包含的输入流中多次重新填充内部缓冲区。标记操作会记住输入流中的一个点,而reset操作会在从包含的输入流中获取新字节之前,重新读取自最近一次标记操作以来读取的所有字节。
有关更多详细信息,请参见https://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html

2
1,2c1,2
< public class FileInputStream
< extends InputStream
---
> public class BufferedInputStream
> extends FilterInputStream
4,8c4,11
< A FileInputStream obtains input bytes from a file in a file system. What files
< are available depends on the host environment.
<
< FileInputStream is meant for reading streams of raw bytes such as image data.
< For reading streams of characters, consider using FileReader.
---
> A BufferedInputStream adds functionality to another input stream-namely, the
> ability to buffer the input and to support the mark and reset methods. When the
> BufferedInputStream is created, an internal buffer array is created. As bytes
> from the stream are read or skipped, the internal buffer is refilled as
> necessary from the contained input stream, many bytes at a time. The mark
> operation remembers a point in the input stream and the reset operation causes
> all the bytes read since the most recent mark operation to be reread before new
> bytes are taken from the contained input stream.

2
嗯,演示得分-1,但厚颜无耻得分+1! - Stephen C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接