-1

I want my program to check if there is data in the text file and add more data below it.

I can write to the file but I don't know how to check if there is already data in the file and how to add more information below it. It currently just overrides the existing information.

try (
FileWriter file = new FileWriter("name.txt");
PrintWriter out = new PrintWriter(file);
Scanner sc = new Scanner(System.in);
) {
out.println("Name:" + firstname + " " + middlename + " " + lastname);
out.println("DOB:" + birthday);
out.println("Phone:" + phone);
out.println("Address:" + address);
} catch(IOException e) {
System.out.println("Error!");
}

It should add more information below the existing information, not replace it.

For example: Name: anon anon anon DOB:010200 Phone:12345678 Address: anon

Then when I run the code again I want it the write the new information below it.

j avi
  • 1

1 Answers1

1
FileWriter file = new FileWriter("name.txt", true);

The FileWriter constructor takes a parameter append. If it is set to true, your data will be appended to the file (i.e. not overwrite it). If it is false, the file is overwritten. Documentation will tell you more.

scatter
  • 903
  • 7
  • 24