在此处提供了一些答案并阅读了一些评论之后,似乎在实践中,文件 I/O 的关闭时永远不会引发 IOException。
是否存在对 Stream/Reader/Writer 调用 close 实际上抛出 IOException 的情况?
如果确实抛出了异常,应该如何处理?
我发现了两个案例:
- 当缓冲区中仍有数据需要刷新时,网络连接丢失。
- 当缓冲区中仍有数据需要刷新时,让文件系统填满(或达到用户的文件大小限制)。
这两个示例都依赖于缓冲区中仍有数据时发生的事情。 Close 在文件关闭之前刷新缓冲区,因此如果将数据写入文件时出错,则会抛出 IOException。
如果执行以下代码并向其传递要在网络驱动器上创建的文件的名称,然后在按 Enter 键之前拔下网络电缆,则会导致程序在关闭时抛出 IOException。
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Test
{
public static void main(final String[] argv)
{
final File file;
file = new File(argv[0]);
process(file);
}
private static void process(final File file)
{
Writer writer;
writer = null;
try
{
writer = new FileWriter(file);
writer.write('a');
}
catch(final IOException ex)
{
System.err.println("error opening file: " + file.getAbsolutePath());
}
finally
{
if(writer != null)
{
try
{
try
{
System.out.println("Please press enter");
System.in.read();
}
catch(IOException ex)
{
System.err.println("error reading from the keyboard");
}
writer.close();
}
catch(final IOException ex)
{
System.err.println("See it can be thrown!");
}
}
}
}
}
从 Java 7 开始,您可以使用 try-with-resources 来摆脱这种混乱(删除了显式异常生成代码)close()
手术):
private static void process(final File file) {
try (final Writer writer = new FileWriter(file)) {
writer.write('a');
} catch (final IOException e) {
// handle exception
}
}
这将自动神奇地处理异常close()
并且它执行显式的null
内部检查。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)