Search code examples
javafileclassobjectprintwriter

Trying to append a text file using java printwriters


So I have a few other classes like this one, I call the method in using an object in the run file. I want to write every output of every class into the same text file. However at the moment only one output is being saved to the text file, as it is overwriting each time, how do I do this using a print writer seen below?

Any guidance is much appreciated!

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

Run File:

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

Solution

  • You want to use the second argument of the FileWriter constructor to set the append mode:

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

    instead of:

    new FileWriter("name_of_your_file.txt");