如何声明和关闭InputSteam?

com*_*ose 4 java exception-handling inputstream

以下哪一项是关闭和声明inputStream的首选方法.

InputStream is = null; 
String md5;
try{
    is = new FileInputStream(FILE.getAbsoluteFile());
    md5 = UTILS.getMD5Info(is);
} finally{
    if(is != null) 
        is.close();
}
Run Code Online (Sandbox Code Playgroud)

要么

InputStream is = new FileInputStream(FILE.getAbsoluteFile()); 
String md5;
try{
    md5 = UTILS.getMD5Info(is);
} finally{
    is.close();
}
Run Code Online (Sandbox Code Playgroud)

我没有看到两者之间有太大差异,但第二种方式看起来更好,因为它有点短.如果我们不想捕获异常并且只是对收集inputStream的垃圾感兴趣,那么在try块中是否有任何初始化输入流的用法?

JB *_*zet 6

如果在try和finally之间捕获到IOException,则第一个也会处理FileInputStream的构造函数抛出IOException,而第二个不抛出IOException的情况.他们不会做同样的事情.原样,第二个更干净.

从Java 7开始,最好的方法是使用try-with-resources语句:

try (InputStream is = new FileInputStream(FILE.getAbsoluteFile())) {
    md5 = UTILS.getMD5Info(is);
}
Run Code Online (Sandbox Code Playgroud)


rle*_*ndi 6

如何使用Java 7功能试用资源

try (InputStream is = new FileInputStream(FILE.getAbsoluteFile())) {
    ...
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

正如它,如果你想成为绝对精确是很丑陋(不要忘记,任何读者可能会引发额外IOExceptionclose()!):

InputStream is = null;

try {
    is = new FileInputStream(FILE.getAbsoluteFile());

    // Your md5() magic here

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在第二个版本中,当构造函数抛出异常时(例如,找不到文件或者您没有访问它的权限)时,不处理这种情况.

如果您也想处理这种情况,则需要InputStreamtry-catch块之前声明(或添加throws IOException到当前函数定义).

不过,你需要检查它是否已正确初始化,即,它是不是nullfinally块.

此外,如果你想要close()流,你必须处理可能的IOException(通常情况下,如果你能够打开流,则永远不会发生).