仅在抛出 IOException 时检查损坏的管道



写入OutputStream时,如果远程计算机关闭或已断开连接,它将引发IOException异常。现在,我想在仅(且仅(管道损坏时调用特定方法。问题是IOException没有codeerrno属性来检查此错误。而我能够实现这一目标的唯一方法是

        try {
            stream.write(message.getBytes("UTF8"));
            stream.flush();
        } catch (IOException e) {
            if (e.getMessage().equals("sendto failed: EPIPE (Broken pipe)")) {
                // perform a specific action
            } else {
                e.printStackTrace();
            }
        }

显然,这不是实现这种事情的完美方法。对有效的解决方案有什么建议吗?

正如这里提到的

在Java中,没有具体的BrokenPipeException。这种类型的 将发现错误包装在不同的异常中,例如 SocketExceptionIOException .

因此,您可以使用String#contains()方法实现相同的效果

if(e.getMessage().contains("Broken Pipe")){
// Do Whatever you want to do 
}