-2

I open file as follows

private static Formatter x;
public static void openFile(){

    try{
        x=new Formatter("sarit.text");
    }
    catch(Exception e){
        System.out.println("error");
    }
}

Here I add a information to the file but the problem of adding the information to this file erases everything that was in the file before inserting the information

public static void addRecords(String age,String city,String name, String password){     
    x.format("    "+name+"  "+password+"    "+age+" "+city+"\n");       
}

public static void closeFile(){
    x.close();
}
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113

2 Answers2

3

Welcome to StackOverflow!

You are doing new Formatter("sarit.text");

Checking javadoc for https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)

if the file exists then it will be truncated to zero size

you need to append to file. Question How to append text to an existing file in Java provides answers how to append to file in java.

Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
0

Assuming you're using java.util.Formatter, the documentation specifically says:

If the file exists then it will be truncated to zero size; otherwise, a new file will be created

You have to find a different way to do it, with a BufferedWriter for example:

BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));

The true parameter tells the FileWriter to append to the file.

If you want to use formatting, use String.format():

writer.write(String.format(...));
SurfMan
  • 1,685
  • 12
  • 19