JAVA打印搜索数组结果到文件

时间:2014-11-20 03:48:01

标签: java arrays design-patterns text-files

在下面的代码中我可以完成我想要对控制台做的事情。 如何在控制台中将相同的数据输出到文本文件?

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

我试图添加

BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("C:/Users/Daniel/Desktop/Cleaned1.txt")));

            bwr.write(stringBuffer.toString());

            bwr.flush();

            bwr.close();

但它只打印带搜索词的最后一个数组。

1 个答案:

答案 0 :(得分:1)

将数据输出到文件中

  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) { }

这会将相同的输出打印到文件