2013-07-04 57 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); 

      } 
    } 
} 
}