FileInputStream 读取方法具有签名(这是正确的术语吗?) -
public int read(byte[] b) throws IOException
// Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.
// Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
拥有这样的签名比这样的签名有什么优势 -
public byte[] read(int numberOfBytes) throws IOException
// Reads up to numberOfBytes bytes of data from this input stream into an array of bytes.
// Returns- an array of bytes read. Array is empty if there is no more data because the end of the file has been reached.
最佳答案
第一种形式允许您在多次执行中重复使用相同的byte[]
数组。基本上,您可以读取产生最少垃圾(低 GC Activity )的整个流。
后者显然更方便,但每次在 read()
方法内部执行时都需要创建 byte[]
的新实例。这意味着在读取 10 GiB 文件(即使是 100 字节 block )时,您的应用程序将总共分配 10 GiB 内存 - 不是同时分配,但垃圾收集器仍然会疯狂工作。
看看Collection.toArray(T[])
- 它遵循相同的原则。
关于java - FileInputStream读取方法的风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9456454/