Suppaa Suppaa - 1 year ago 67
Java Question

Overwriting output in textfile (need to save all outputs) [Solved]

Hey guys I need my program to be able store multiple outputs, but instead it is just overwriting the same string (total) over and over in the textfile. How can i make it so it will write multiple answers instead of overwriting it? Thank you :)

static int boys;
static int girls;
static int total;

public static void program() {

System.out.println("enter number of girls: ");
girls = input.nextInt();
System.out.println("enter number of boys: ");
boys = input.nextInt();
total = boys+girls;



private static Formatter x;

public void openFile () {
try {
x = new Formatter("income.txt");

catch(Exception e) {
System.out.println("You have an error");

public static void addRecords(){
x.format("%s%s%s", " 19", " James", " A");
x.format("%s%s", "\n", total);


public void closeFile(){

Answer Source

You can change your openFile method to something like this:

public void openFile(){
    try {
        Appendable appendable = new FileWriter("income.txt",true);
        x = new Formatter(appendable);
    } catch(Exception e) {
        System.out.println("You have an error");

The important part is new FileWriter("income.txt",true);, this creates a new FileWriter that appends data to the income.txt file.

You can find more info about that HERE

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download