如何检查OutputStream是否已关闭 [英] How to check whether an OutputStream is closed

查看:804
本文介绍了如何检查OutputStream是否已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何检查OutputStream是否关闭而不尝试写入它并捕获 IOException



<例如,考虑以下设计方法:

  public boolean isStreamClosed(OutputStream out){
if(/ *流未关闭* /){
返回true;
} else {
返回false;
}
}

你可以替换什么 / *流未关闭* / 与?

解决方案

基础流可能不知道它的关闭,直到你试图写入它(例如,如果套接字的另一端关闭它)



最简单的方法是使用它并处理如果它关闭然后会发生什么而不是先测试它。



无论你测试什么,总有可能得到IOException,所以你无法避免异常处理代码。添加此测试可能会使代码复杂化。


Is there anyway to check whether an OutputStream is closed without attempting to write to it and catching the IOException?

For example, consider the following contrived method:

public boolean isStreamClosed(OutputStream out){
    if( /* stream isn't closed */){
        return true;
    }else{
        return false;
    }
}

What could you replace /* stream isn't closed */ with?

解决方案

The underlying stream may not know it its closed until you attempt to write to it (e.g. if the other end of a socket closes it)

The simplest approach is to use it and handle what happens if it closed then, rather than testing it first as well.

No matter what you test, there is always the chance you will get an IOException, so you cannot avoid the exception handling code. Adding this test is likely to complicate the code.

这篇关于如何检查OutputStream是否已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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