重用输入流变量

Reusing the input stream variable

考虑以下代码片段 getInputStreamForRead() 方法创建并 returns 一个新的输入流以供读取。

InputStream is = getInputStreamForRead();    //This method creates and returns an input stream for file read
is = getDecompressedStream(is);

由于原始文件内容是压缩存储的,因此在阅读时需要解压。因此 getDecompressedStream() 下面的方法将提供解压缩流内容的选项

public InputStream getDecompressedStream(InputStream is) throws Exception {
 return new GZIPInputStream(is);
}

有以下疑惑

  1. 以上代码片段中哪一个是正确的

    is = getDecompressedStream(is) 
    

    InputStream newStream = getDecompressedStream(is)
    
  2. 再次使用InputStream变量会不会有什么麻烦?

我对流完全陌生。请帮助我了解这件事。

只要:

  • 您没有在原始赋值和新调用之间操纵原始 InputStream
  • 您总是在 finally 语句中关闭您的流

...您应该重新分配给原始变量 - 它只是传递给现有引用的新值。

事实上,这可能是推荐的方式,因为您只能以编程方式关闭一个 Closeable,因为 GZIPInputStream#close...

Closes this input stream and releases any system resources associated with the stream.

(参见 here - 我将其解读为 "closes the underlying stream")。

既然你想正确关闭输入流,最好的方法是使用链接创建输入流,并使用 try-with-resources 来为你处理关闭。

try (InputStream is = getDecompressedStream(getInputStreamForRead())) {
    // code using stream here
}