How to write more than one object result to one output text file in Java?

I have multiple objects with different output and I want to print all results in one text file, each object result in one line without overwriting any values.

I wrote the following code; however, the output text file only retains the values โ€‹โ€‹of the last object (Object2). I want the output file to save the result like this:

Q = 1    
Q = 2

      

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Output {
    public static int Q;

    public static void main(String[] args) {
        Object1();
        Object2();
    }

    public static void Object1() {
        Q = 1;
        Print();
    }

    public static void Object2() {
        Q = 2;
        Print();
    }

    public static void Print() {
        PrintWriter writer;
        try {
            writer = new PrintWriter("C:\\Users\\My Document\\Desktop\\Out.txt");
            if (Q == 1) {
                writer.println("Q =" + 1);
            }
            if (Q == 2) {
                writer.println("Q = " + 2);
            }
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

      

+3


source to share


2 answers


You are overwriting your Out.txt

file with new information. You need to add your details.

Replace your line like this:



writer = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\My Document\\Desktop\\Out.txt", true)));

      

+1


source


A FileWriter

is the correct way to get around this. You also don't need to wrap it.

The assignment true

in the constructor enables add mode (so be careful on subsequent runs). Since Q cannot be both 1 and 2, we write a new line after we are done with the block.



Since this is a try-with-resources statement, you don't need to worry about closing the resource when you're done, as it is taken care of.

try (FileWriter writer = new FileWriter("test.txt", true)) {
    if (Q == 1) {
        writer.write("Q =" + 1);
    }
    if (Q == 2) {
        writer.write("Q = " + 2);
    }
    writer.write("\n");
} catch (IOException e) {
    e.printStackTrace();
}

      

+2


source







All Articles