Java filewriter 只将最后一行写入文件?

Java filewriter only writing last line to file?

它目前所做的是从一个文本文件中读取数据并以指定的方式输出它们。当我将它输出到控制台时,它会以所需的方式显示它,但是当我尝试将它输出到文本文件时,由于某种原因它只会写入循环的最后一行。这是我必须处理文件输出的代码:

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

    String gt;
    String gt2;
    int gs1;
    int gs2;
    int total = 0;


    Scanner s = new Scanner(new BufferedReader(
            new FileReader("input.txt"))).useDelimiter("\s*:\s*|\s*\n\s*");

    while (s.hasNext()) {
        String line = s.nextLine();
        String[] words = line.split("\s*:\s*");
        //splits the file at colons

        if(verifyFormat(words)) {
            gt = words[0];       // read the home team
            gt2 = words[1];       // read the away team
            gs1 = Integer.parseInt(words[2]);       //read the home team score
            total = total + gs1;
            gs2 = Integer.parseInt(words[3]);       //read the away team score
            total = total + gs2;
            validresults = validresults + 1;


            File file = new File("out.txt");
            FileOutputStream fos = new FileOutputStream(file);
            PrintStream ps = new PrintStream(fos);
            System.setOut(ps);
            System.out.println(gt + " " +  "[" + gs1 + "]" +  " | " + gt2 + " " + "[" + gs2 + "]");   
            //output the data from the file in the format requested

        }
        else{
            invalidresults = invalidresults + 1;
        }
    }

每次调用 FileOutputStreamPrintStream 的构造函数时,就像重新开始一样。这些对象不再知道它们应该存储有关循环的前一次迭代的信息,因为它们是刚刚构造的。将所有这些构造函数移出循环并仅调用一次将解决您的问题。即

 File file = new File("out.txt");
 FileOutputStream fos = new FileOutputStream(file);
 PrintStream ps = new PrintStream(fos);
 System.setOut(ps);

应该在进入循环之前创建(一次!)while(s.hasNext())

每个输入行,您都在创建一个新的输出文件并覆盖旧的。这是因为创建文件的代码在循环内!

移动这些行:

File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);

while (s.hasNext())

之前