我多次调用这个方法:
private static void writeFile(double val, String myFile) throws IOException { FileWriter file = new FileWriter(myFile, true); file.write(val + "\n"); file.close(); }
一段时间后我有这个异常(exception):
Exception in thread "main" java.io.FileNotFoundException: myFile (Too many open files)
请问我该如何解决这个异常?
最佳答案
我猜你的一些(也许是全部)文件写入会导致异常,从而使 file.close() 短路。即使不是这种情况,通常的做法是将您的文件 IO 操作包装在 try/catch/finally 中,以确保无论读/写是否成功,您打开的任何内容都会关闭。如果不关闭文件,您将用完句柄。
private static void writeFile(double val, String myFile) throws IOException {
FileWriter file = null;
try {
file = new FileWriter(myFile, true);
file.write(val + "\n");
} catch( IOException e ) {
e.printStackTrace();
} finally {
if( file != null ) {
file.close();
}
}
}
或者,如果使用 JDK 1.7:
private static void writeFile(double val, String myFile) throws IOException {
try (FileWriter file = new FileWriter(myFile, true)) {
file.write(val + "\n");
} catch( IOException e ) {
e.printStackTrace();
}
}
关于java - Java 中打开的文件太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889272/