尝试使用 java printwriters 附加文本文件

Trying to append a text file using java printwriters

所以我还有其他一些像这样的 classes,我在 运行 文件中调用使用对象的方法。我想将每个 class 的每个输出写入同一个文本文件。但是目前只有一个输出被保存到文本文件中,因为它每次都会被覆盖,我该如何使用下面看到的打印器来做到这一点?

非常感谢任何指导!

Class:

 package cw;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;

public class LineCounter {

    public static void TotalLines() throws IOException {
        Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
         PrintWriter out = new PrintWriter(new FileWriter("C:\Users\Sam\Desktop\Report.txt"));
        int linetotal = 0;
        while (sc.hasNextLine()) {
            sc.nextLine();
            linetotal++;
        }
         out.println("The total number of lines in the file = " + linetotal);


         out.close();
         System.out.println("The total number of lines in the file = " + linetotal);
    }
}

运行 文件:

package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;

public class TextAnalyser {

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

        Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));




        LineCounter Lineobject = new LineCounter();
        WordCounter Wordobject = new WordCounter();
        NumberCounter Numberobject = new NumberCounter();
        DigitCounter Digitobject = new DigitCounter();
        SpaceCounter Spaceobject = new SpaceCounter();
        NumberAverage Noavgobject = new NumberAverage();
        WordAverage Wordavgobject = new WordAverage();
        Palindromes Palindromeobject = new Palindromes();
        VowelCounter Vowelobject = new VowelCounter();
        ConsonantCounter Consonantobject = new ConsonantCounter();
        WordOccurenceTotal RepeatsObject = new WordOccurenceTotal();


        Lineobject.TotalLines();
        Wordobject.TotalWords();
        Numberobject.TotalNumbers();
        Digitobject.TotalDigits();
        Spaceobject.TotalSpaces();
        Noavgobject.NumberAverage();
        Wordavgobject.WordAverage();
        Vowelobject.TotalVowels();
        Consonantobject.TotalConsonant();
        Palindromeobject.TotalPalindromes();

       //RepeatsObject.TotalRepeats();
    }
}

您想使用 FileWriter 构造函数的第二个参数来设置追加模式:

new FileWriter("name_of_your_file.txt", true);

而不是:

new FileWriter("name_of_your_file.txt");