我只是想将我的二维数组“拼图”写入文件。我有一个双 for 循环,它读取数组中的每个“char”值,并将它们写入文件。我似乎无法在我的代码中找到错误。该文件说当我运行程序时它已被修改,但它仍然是空白的。多谢你们!
public void writeToFile(String fileName)
{
try{
PrintWriter pW = new PrintWriter(new File(fileName));
for(int x = 0; x < 25; x++)
{
for(int y = 0; y < 25; y++)
{
pW.write(puzzle[x][y]);
}
pW.println();
}
}
catch(IOException e)
{
System.err.println("error is: "+e.getMessage());
}
}
在finally 块中关闭PrintWriter 以刷新它并回收资源
public void writeToFile(String fileName) {
// **** Note that pW must be declared before the try block
PrintWriter pW = null;
try {
pW = new PrintWriter(new File(fileName));
for (int x = 0; x < 25; x++) {
for (int y = 0; y < 25; y++) {
pW.write(puzzle[x][y]);
}
pW.println();
}
} catch (IOException e) {
// System.err.println("error is: "+e.getMessage());
e.printStackTrace(); // *** this is more informative ***
} finally {
if (pW != null) {
pW.close(); // **** closing it flushes it and reclaims resources ****
}
}
}
警告:代码未经测试或编译。
请注意,另一个选项是使用尝试使用资源 http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)