2012-02-26 39 views
2

FileInputStream中读出方法签名(是正确的术语?) -风格的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. 

回答

4

第一种形式允许您重复使用相同的byte[]阵列进行多次执行。基本上你可以读取生成最少垃圾的全部流(低GC活性)。

后者显然更方便,但需要在read()方法内部每次执行内部时创建byte[]的新实例。这意味着在读取10个GiB文件(即使是100字节的块)时,应用程序总共会分配10吉比特的内存 - 而不是同时,但垃圾收集器仍然会像疯狂一样工作。

看看Collection.toArray(T[]) - 它遵循相同的原则。

+0

后面的一个更方便吗? – UnKnown 2016-03-29 09:01:44