Java 在特殊情况下如何关闭文件?
试想一下,当我打开文件时,当我想在其中写入内容时,会抛出一个异常,如果我在try块中使用file.close(),那么由于该异常将无法工作,Java 在特殊情况下如何关闭文件?,java,file,Java,File,试想一下,当我打开文件时,当我想在其中写入内容时,会抛出一个异常,如果我在try块中使用file.close(),那么由于该异常将无法工作, 我应该在哪里关闭文件?您应该使用finally块。然而close方法也可以抛出IOException,所以您也应该将其包围在try-catch块中 这可能会有帮助。您应该使用finally块。然而close方法也可以抛出IOException,所以您也应该将其包围在try-catch块中 这可能会有帮助。使用finally块: File f; try {
我应该在哪里关闭文件?您应该使用finally块。然而close方法也可以抛出IOException,所以您也应该将其包围在try-catch块中
这可能会有帮助。您应该使用finally块。然而close方法也可以抛出IOException,所以您也应该将其包围在try-catch块中 这可能会有帮助。使用finally块:
File f;
try {
f = ....
.. use f ...
} /* optional catches */
finally {
if (f != null) f.close();
}
使用finally块:
File f;
try {
f = ....
.. use f ...
} /* optional catches */
finally {
if (f != null) f.close();
}
我使用两个试接块 我打开文件的地方+一个bool,让我知道文件已成功打开。 第二个是我写东西的地方(在检查bool是否打开成功之后)
我使用两个试接块 我打开文件的地方+一个bool,让我知道文件已成功打开。 第二个是我写东西的地方(在检查bool是否打开成功之后)
正确的方法是:
FileOutputStream out = null;
try {
out = ...
...
out.write(...);
...
out.flush();
} catch (IOException ioe) {
...
} finally {
if(out!=null) {
try {
out.close();
} catch (IOException ioe) {
...
}
}
}
正确的方法是:
FileOutputStream out = null;
try {
out = ...
...
out.write(...);
...
out.flush();
} catch (IOException ioe) {
...
} finally {
if(out!=null) {
try {
out.close();
} catch (IOException ioe) {
...
}
}
}
David Rabinowitz的答案是正确的,但通过使用。对于finally子句中复杂的try块,它有一个方法,可以毫无例外地关闭任何流。有了这个,你可以写下:
FileOutputStream out = null;
try {
out = ...
...
out.write(...);
...
out.flush();
} catch (IOException ioe) {
...
} finally {
if(out!=null) {
org.apache.commons.io.IOUtils.closeQuietly(out);
}
}
David Rabinowitz的答案是正确的,但通过使用。对于finally子句中复杂的try块,它有一个方法,可以毫无例外地关闭任何流。有了这个,你可以写下:
FileOutputStream out = null;
try {
out = ...
...
out.write(...);
...
out.flush();
} catch (IOException ioe) {
...
} finally {
if(out!=null) {
org.apache.commons.io.IOUtils.closeQuietly(out);
}
}
资源的一般模式是
acquire;尝试{use;}最后{release;}
。如果你试图重新安排,你经常会遇到这样的情况,比如说,你释放了一个锁却没有得到它。注意,一般来说,没有必要使用空检查来混乱。如果需要捕获所有代码中的异常,请使用try catch
环绕所有代码。所以
try {
final InputStream in = new FileInputStream(file);
try {
...
} finally {
in.close();
}
} catch (IOException exc) {
throw new SomeException(exc);
}
资源的一般模式是
acquire;尝试{use;}最后{release;}
。如果你试图重新安排,你经常会遇到这样的情况,比如说,你释放了一个锁却没有得到它。注意,一般来说,没有必要使用空检查来混乱。如果需要捕获所有代码中的异常,请使用try catch
环绕所有代码。所以
try {
final InputStream in = new FileInputStream(file);
try {
...
} finally {
in.close();
}
} catch (IOException exc) {
throw new SomeException(exc);
}
当我在finally块中写入file.close()时,它将显示创建名为file.:(当我在finally块中写入file.close()时,它将显示创建名为file.:(的局部变量)的错误(close抛出IOException在我看来是一个糟糕的设计决策。close抛出IOException在我看来是一个糟糕的设计决策。