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

时间:2015-03-24 19:04:26

标签: java file class object printwriter

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

非常感谢任何指导!

班级:

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

1 个答案:

答案 0 :(得分:2)

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

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

而不是:

new FileWriter("name_of_your_file.txt");