Search code examples
javafilewriter

How do I get matcher.find while loop to write to text file? java


I'm using a while(matcher.find()) loop to write certain substrings to a file. I get a list of the matched strings occurring in the file in my System.out console just fine, but when I try to use FileWriter to write to a text file, I only get the very last string in the loop written. I've scoured stackoverflow for similar problems (and it lives up to its name), I couldn't find anything that helped me. And just to clarify this isn't being run on the EDT. Can anyone explain where to look for the problem?

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);

            }
    }
}

Solution

  • Quick fix:

    change

    newerFile = new FileWriter(writePath);
    

    to

    newerFile = new FileWriter(writePath, true);
    

    This uses the FileWriter(String fileName, boolean append) constructor.


    Better fix:

    create the FileWriter outside of the while(matcher.find()) loop and close it afterwards (or use it as a try with resources initilzation).

    the code would be something like:

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