0

I am writing a simple program which asks the user for his name, surname and age and then saves it to a text file, however the previous data gets deleted. I am already reading the text file and can display it but I cant write it to the text file.

This is the code I am using:

import java.util.Scanner;
import java.io.*;
public class UserData{
public static void main (String args[]) throws IOException{
    //Initialisations
    Scanner scan = new 
    Scanner(System.in);
    File UserData = new File(PATH OF FILE);
    BufferedWriter b = new BufferedWriter(new FileWriter(UserData));


    //Reader for Writer Old Data
    String text[] = new String[10];
    int count = 0;
    String path = PATH OF FILE;
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    while ((line = reader.readLine()) != null){
        text[count] = line;
        count++;
    }

    PrintWriter pr = new PrintWriter(PATH OF FILE);    
    for (int I=0; I<text.length ; I++)
    {
        pr.println(text);
    }



    //Writer
    System.out.println("Enter your name");
    String name = scan.nextLine();
    pr.println(name);
    b.newLine();
    System.out.println("Enter your surname");
    String surname = scan.nextLine();
    pr.println(surname);
    b.newLine();
    System.out.println("Enter your age");
    int age = scan.nextInt();
    pr.println(String.valueOf(age));
    pr.close();
}

}

  • So you need to append data to your current data file? – Jay Apr 22 '19 at 08:54
  • Please refer https://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode new FileWriter(UserData, true); – R.G Apr 22 '19 at 09:00
  • I have tested you code and it write corretly a text file. You must sure that your file path is correct! – Bogojob Apr 22 '19 at 09:10

1 Answers1

2

FileWriter class has a constructor

public FileWriter(File file,
          boolean append)
           throws IOException

Constructs a FileWriter object given a File object.

In Your code - Change line no 9 to

BufferedWriter b = new BufferedWriter(new FileWriter(UserData),true);

If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Here is the specification: Class FileWriter Constructors

Nitika Bansal
  • 740
  • 5
  • 10