0

我正在使用 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);

            }
    }
}
4

3 回答 3

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());
   }
} ...
于 2013-07-04T09:09:59.363 回答
0

您不应该创建FileWriter每个循环迭代的实例。您需要将方法的使用write()留在那里并在循环之前初始化并FileWriter在循环之后关闭它。

于 2013-07-04T09:12:20.950 回答
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);

            }
    }
}
}
于 2013-07-04T09:39:45.517 回答