gpt4 book ai didi

java - 重用输入流变量

转载 作者:行者123 更新时间:2023-12-02 03:29:01 25 4
gpt4 key购买 nike

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

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 - 我将其理解为“关闭底层流”)。

关于java - 重用输入流变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38355918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com