如何在循环写入文本文件时获取matcher.find? java的

时间:2013-07-04 09:08:08

标签: java filewriter

我正在使用while(matcher.find())循环将某些子字符串写入文件。我得到了System.out控制台中文件中出现的匹配字符串列表,但是当我尝试使用FileWriter写入文本文件时,我只得到循环写入的最后一个字符串。我已经为类似的问题搜索了stackoverflow(并且它的名字不变),我找不到任何帮助我的东西。而且只是为了澄清这一点并没有在EDT上运行。任何人都可以解释在哪里寻找问题吗?

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 个答案:

答案 0 :(得分:3)

快速修复:

变化

newerFile = new FileWriter(writePath);

newerFile = new FileWriter(writePath, true);

这使用FileWriter(String fileName, boolean append)构造函数。


更好的解决方法:

FileWriter循环之外创建while(matcher.find())并在之后将其关闭(或将其用作try with resources初始化)。

代码如下:

try (FileWriter newerFile = new FileWriter(writePath)) {
   while (matcher.find()) {
      newerFile.write(matcher.group());
   }
} ...

答案 1 :(得分:0)

您不应该在每次循环迭代时创建FileWriter的实例。您需要在循环之前保留方法write()的使用和init FileWriter,并在循环之后将其关闭。

答案 2 :(得分: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);

            }
    }
}
}