2014-09-20 78 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