2013-07-04 58 views
0

我正在使用while(matcher.find())循環來將特定的子字符串寫入文件。我在System.out控制檯的文件中獲得了匹配字符串的列表,但是當我嘗試使用FileWriter寫入文本文件時,我只能得到寫入的最後一個字符串。我已經爲類似的問題搜索了stackoverflow(並且它的名字真實),我找不到任何幫助我的東西。而僅僅爲了澄清這一點,美國東部時間並未運行。任何人都可以解釋在哪裏尋找問題?如何在循環寫入文本文件時獲取matcher.find? java

try { 
    String writeThis = inputId1 + count + inputId2 + link + inputId3; 
    newerFile = new FileWriter(writePath); 
    //this is only writing the last line from the while(matched.find()) loop 
    newerFile.write(writeThis); 
    newerFile.close(); 
    //it prints to console just fine! Why won't it print to a file? 
    System.out.println(count + " " + show + " " + link); 
    } catch (IOException e) { 
     Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, e); 
    } finally { 
     try { 
      newerFile.close(); 
      } catch (IOException e) { 
       Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, e); 

      } 
    } 
} 

回答

3

快速修復:

變化

newerFile = new FileWriter(writePath); 

newerFile = new FileWriter(writePath, true); 

它使用FileWriter(String fileName, boolean append)構造。


更好的解決辦法:

創建FileWriterwhile(matcher.find())環,之後將其關閉(或使用它作爲一個try with resources initilzation)。

代碼將是這樣的:

+0

啊是的,我在循環內創建FileWriter,沒有附加開關lol ......謝謝:) – Grux

0

你不應該創建的FileWriter每次循環的實例。您需要在循環前使用方法write(),並在循環之前使用init FileWriter,並在循環之後關閉它。

0
Please check as follows: 

FileWriter newerFile = new FileWriter(writePath); 
while(matcher.find()) 
{ 
xxxxx 
try { 
    String writeThis = inputId1 + count + inputId2 + link + inputId3; 

    //this is only writing the last line from the while(matched.find()) loop 
    newerFile.write(writeThis); 
    newerFile.flush(); 
    //it prints to console just fine! Why won't it print to a file? 
    System.out.println(count + " " + show + " " + link); 
    } catch (IOException e) { 
     Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, e); 
    } finally { 
     try { 
      newerFile.close(); 
      } catch (IOException e) { 
       Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, e); 

      } 
    } 
} 
}