-1

假设 Java6,此代码是否可以避免文件描述符泄漏:

{
    InputStream in = fileObject.getReadStream();
    // fileObject cleans it's internal state in case it throws exception
    try {
        // do whatever, possibly throwing exception
    } finally {
        try {
            in.close();
        } catch (Exception ex) {
            // failure to close input stream is no problem
        }
    }
}

编辑:为了让问题看起来不那么明显,换句话说,上面的代码等于这个更长的代码:

{
    InputStream in = null;
    try {
        in = fileObject.getReadStream();
        // fileObject cleans it's internal state in case it throws exception

        // do whatever, possibly throwing exception
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception ex) {
                // failure to close input stream is no problem
            }
        }
    }
}

也就是说,对返回打开的流或抛出异常的方法的调用是紧接在 之前try还是在try块内是否重要?

4

2 回答 2

2

是的,很好。甚至不值得回答。一个变体(我较少使用)是:

InputStream in = null;
try {
    in = fileObject.getReadStream();
    // do whatever, possibly throwing exception
} finally {
    if (in  != null) {
        try {
           in.close();
        } catch (Exception ex) {
            // failure to close input stream is no problem if everything else was ok
        }
    }
}
于 2013-03-12T10:08:03.933 回答
-1

我是一个对Java不太熟悉的学生,但我希望能对你有所帮助。我认为这段代码不能让你避免文件描述符泄漏的问题。尽管您已经尝试关闭 in.close 方法,但是如果 in.close 方法抛出一些异常,这将无济于事。

于 2013-03-12T10:12:36.973 回答