Java PrintWriter无法正常工作

cha*_*ker 2 java file-io printwriter

我只是想把我的二维数组"拼图"写到一个文件中.我有一个双循环,它读取我的数组中的每个'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());
  }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 9

在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 ****
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

警告:代码未经测试或编译.

请注意,另一个选项是使用try with resources.