在Java中,FileInputStream和BufferedInputStream有何区别?
在Java中,FileInputStream和BufferedInputStream有何区别?
关键区别:
BufferedInputStream
有缓冲区,但FileInputStream
没有。
BufferedInputStream
从另一个InputStream
读取数据,而FileInputStream
从文件中读取1。
实际上,这意味着每次调用FileInputStream.read()
会执行系统调用(开销很大)...而大多数调用BufferedInputStream.read()
将从缓冲区返回数据。简而言之,如果进行“小”的读取,将BufferedInputStream
放入流堆栈中将提高性能。
对于大多数目的/用例,这就是所有相关的内容了。
还有一些其他的东西(如标记/重置/跳过),但这些都是比较专业的...
有关更详细的信息,请阅读Java文档...以及源代码。
1-或者更准确地说,从一些在操作系统的“文件系统”命名空间中具有名称的对象和操作系统允许您作为字节序列读取的对象中读取。这可能包括设备、命名管道和其他各种不被视为“文件”的东西。还值得注意的是,有一些类型的东西绝对不能使用FileInputStream
读取。
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
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.