Q:

JAVA Print search array results to file

in the following code i can complete the what i am trying to do TO THE CONSOLE.
how do i output the same data in the console to a text file?
package javaapplication4;
import java.io.*;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

public class JavaApplication4 {

    public static void main(String[] args) throws IOException {

        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader("C:/Users/Daniel/Desktop/Cleaned.txt")));
            s.useDelimiter("\\*");
            String total = (s.next());
            Pattern p = Pattern.compile("\\n[\\n]+");

            String[] parts = p.split(total);

            boolean searchArrayResult = false;
            for (String str : parts) {
                searchArrayResult = str.contains("1ST COAT   BASIS WT");
                if (searchArrayResult) {
                    System.out.println(str);
                } 

            }
            while (s.hasNext()) {

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
}

i have tried to adding
BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("C:/Users/Daniel/Desktop/Cleaned1.txt")));

            bwr.write(stringBuffer.toString());

            bwr.flush();

            bwr.close();

but it will only print the last array with the search term.

A:

output the data into file like this
  try {
        s = new Scanner(new BufferedReader(new FileReader("C:/Users/Daniel/Desktop/Cleaned.txt")));
        s.useDelimiter("\\*");
        String total = (s.next());
        Pattern p = Pattern.compile("\\n[\\n]+");

        String[] parts = p.split(total);

        boolean searchArrayResult = false;
        java.io.File targetFile =new java.io.File("op.txt");
        java.io.FileWriter filew=new java.io.FileWriter(targetFile);
        java.io.PrintWriter print=new java.io.PrintWriter(filew,true);
         for (String str : parts) {
            searchArrayResult = str.contains("1ST COAT   BASIS WT");
            if (searchArrayResult) {
                //System.out.println(str);
                print.println(str);
              }
           }
        while (s.hasNext()) {
        }
     } catch (Exception ex) { }

this will print the same output to the file

