编程语言
首页 > 编程语言> > Java 8 FilterOutputStream异常

Java 8 FilterOutputStream异常

作者:互联网

这是对Java 8中的FilterOutputStream.close()方法的更改,它导致了一些问题. (见http://hg.openjdk.java.net/jdk8/jdk8/jdk/rev/759aa847dcaf)

在以前的Java版本中,以下代码无需抛出异常即可运行.但是,在Java 8下,当try-with-resources机制关闭流时,我们总是会遇到异常.

try( InputStream bis = new BufferedInputStream( inputStream );
     OutputStream outStream = payloadData.setBinaryStream( 0 );
     BufferedOutputStream bos = new BufferedOutputStream( outStream );
     DeflaterOutputStream deflaterStream = new DeflaterOutputStream(
         bos, new Deflater( 3 ) ) )
{
    fileSize = IOUtil.copy( bis, deflaterStream );
}

try-with-resources机制将首先在deflaterStream上调用close().由于deflaterStream包装了包装outStream的bos,deflaterStream.close()将调用bos.close(),它将调用outStream.close()来关闭数据库的底层流.

try-with-resources机制接下来将调用bos上的close().由于bos扩展了FilterOutputStream,因此首先在outStream上调用flush().但是,由于outStream已经关闭,outStream.flush()抛出异常:java.sql.SQLException:Closed LOB

caused by: java.io.IOException: Closed LOB
     at oracle.jdbc.driver.OracleBlobOutputStream.ensureOpen(OracleBlobOutputStream.java:265)
     at oracle.jdbc.driver.OracleBlobOutputStream.flush(OracleBlobOutputStream.java:167)
     at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:141)
     at java.io.FilterOutputStream.close(FilterOutputStream.java:158)
     at com.blah.uploadFile(CustomerUploadFacade.java:162)
     ... 38 more
Caused by: java.sql.SQLException: Closed LOB
     at oracle.jdbc.driver.OracleBlobOutputStream.ensureOpen(OracleBlobOutputStream.java:257)
     ... 42 more

还有其他人遇到过这个问题吗?如果是这样,你是如何解决它的?我们使用try-with-resources的方式有问题吗?

解决方法:

这是FilterOutputStream中的一个错误.这实现了Closable.此接口的合同规定:

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.

所以第二次调用.close()应该没有效果,但是在这种情况下它会调用flush()来抛出异常.

FilterOutputStream停留在继承层次结构中,因此在问题点应用修复并不容易.

如果未在try块中将某些流声明为局部变量,则会导致FindBugs和Eclipse等工具将代码标记为资源使用情况.后来查看此代码的勤奋开发人员可能会想到同样的事情.

您可以创建一个类,CloseOnceBufferedOutputStream,它扩展了BufferedOutputStream.它将有一个布尔值来记住它是否已经关闭,以便它可以满足合同.重写close()方法以检查流是否已关闭.如果是这样,那就回来吧.

如果Oracle修复了底层错误,那么您的新类将无用,但代码将继续有效.

标签:java,io,try-with-resources
来源: https://codeday.me/bug/20190628/1320770.html