【问题标题】:Java Resource LeakJava 资源泄漏
【发布时间】:2015-07-02 06:28:53
【问题描述】:

我的应用程序中有这个代码 sn-p,我很确定我有 关闭所有流。

但是,令人惊讶的是,我不断得到: 在附加的堆栈跟踪中获取了资源,但从未释放。有关避免资源泄漏的信息,请参阅 java.io.Closeable。 java.lang.Throwable:未调用显式终止方法“关闭”

任何指针都会非常有用。

if (fd != null) {
    InputStream fileStream = new FileInputStream(fd.getFileDescriptor());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    try {
        for (int readNum; (readNum = fileStream.read(buf)) != -1;) {
            bos.write(buf, 0, readNum);
        }
        content = bos.toByteArray();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {

            if (fileStream != null) {
                fileStream.close();
            }

            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • 抱歉,我错过了将代码添加到问题中。

标签: java fileinputstream resource-leak


【解决方案1】:

尝试将流的实例化移动到try

InputStream fileStream = null;
ByteArrayOutputStream bos = null;
byte[] buf = new byte[1024];
try {

  fileStream = new FileInputStream(fd.getFileDescriptor());
  bos = new ByteArrayOutputStream();

【讨论】:

【解决方案2】:

尝试对资源使用 try。这消除了在 finally 块中关闭资源的需要。 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

if (fd != null) {
    byte[] buf = new byte[1024];
    try (InputStream fileStream = new FileInputStream(fd.getFileDescriptor());
         ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        for (int readNum; (readNum = fileStream.read(buf)) != -1;) {
            bos.write(buf, 0, readNum);
        }
        content = bos.toByteArray();
    } catch (IOException ex) {
        ex.printStackTrace();
    } 
}

【讨论】:

    【解决方案3】:

    对资源使用 try 可以解决问题。 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html。您可以在这里查看 AutoCloseable 接口,该接口已在 Java 7 http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html中引入

    【讨论】:

      【解决方案4】:

      我看到的是,如果在关闭 fileStream 时发生异常,则 bos 不会被关闭。

      如前所述:使用 try-with-resources 语句: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

      【讨论】:

        猜你喜欢
        • 2012-10-23
        • 1970-01-01
        • 1970-01-01
        • 2014-02-10
        • 1970-01-01
        • 2020-12-09
        • 1970-01-01
        • 1970-01-01
        • 2014-06-30
        相关资源
        最近更新 更多