从getInputStream正确关闭Java Process InputStream [英] Properly closing Java Process InputStream from getInputStream

查看:479
本文介绍了从getInputStream正确关闭Java Process InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中找不到对此的澄清. 但是当我们有一个Process对象并调用getInputStream()时,

I could not find clarification of this in the documentation. But when we have a Process object and call getInputStream(),

我们是否得到一个新的流,当我们完成它时,我们应该明确地关闭它? 或者 我们是否获得了与流程相关联的已经存在的,我们不应该关闭的流,但是流程将负责关闭它?

Do we get a new stream that we should explicitly close when we are done with it? or do we get the stream that is already there, associated with the Process, that we should not close, but the Process would take care of closing it?

基本上,我们应该如何与从Process.getInputStream()获得的流进行交互?关闭还是不关闭?

Basically, how should we interact with the stream we get from Process.getInputStream()? close or not to close?

推荐答案

我的第一个反应是关闭它,您总是关闭打开的流.我确实意识到该文档的质量不尽人意,但是由于它们没有明确声明请勿关闭对我来说意味着遵循良好的编程习惯.

My first reactions was to close it, you always close streams that you open. I do realize the documentation is not up to par, but since they don't explicitly state do not close that to me means follow good programming practices.

InputStream is = process.getInputStream()
try {
    // your code
} finally {
    try { is.close(); } catch (Exception ignore) {}
}

如果您需要确保这没有问题,只需编写一个快速测试用例,即可在每次打开和关闭InputStream时从输入流中受益数十次.

If you need to make sure this isn't problematic, just write a quick test case where you great from the input stream a few dozen times, each time opening and closing the InputStream.

这篇关于从getInputStream正确关闭Java Process InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆