2014-09-20 72 views
1

我只是试图写我的2D阵列“拼图”到一个文件。我有一个double循环,它读取数组中的每个'char'值,并假定将它们写入文件。我似乎无法找到我的代码中的错误。该文件说它在我运行程序时被修改,但它仍然是空白的。多谢你们!Java PrintWriter不起作用

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()); 
    } 
} 

回答

7

闭上你的PrintWriter在finally块来冲洗,并回收资源

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 **** 
    } 
    } 
} 

警告:代码没有测试,也没有编制。

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

+0

给了一个尝试,它在最后的声明中找不到pW - 说“找不到符号:PW” – user43043 2014-09-20 15:30:23

+0

@ user3908256:仔细看看我的例子,尤其是我***声明*** pW变量 - 我在**上面尝试**尝试块。 – 2014-09-20 15:30:54

+0

AHH对不起 - 让我试试 – user43043 2014-09-20 15:31:08