Java PrintWriter 不工作 [英] Java PrintWriter not working
本文介绍了Java PrintWriter 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想将我的二维数组拼图"写入文件.我有一个双 for 循环,它读取数组中的每个char"值,并将它们写入文件.我似乎无法在我的代码中找到错误.该文件说它在我运行程序时被修改,但它仍然是空白的.谢谢各位!
I am simply trying to write my 2d array "puzzle" to a file. I have a double for loop which reads through each of the 'char' values in my array and supposedly writes them to the file. I can't seem to find the error in my code. The file says it is modified when I run the program, but it is still blank. Thanks guys!
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 以刷新它并回收资源
Close your PrintWriter in a finally block to flush it and to reclaim resources
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 ****
}
}
}
警告:代码未经测试或编译.
Caveat: Code not tested nor compiled.
请注意,另一种选择是使用尝试使用资源.
Note that another option is to use try with resources.
这篇关于Java PrintWriter 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文