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();
}

}

3
  • So you need to append data to your current data file? Commented Apr 22, 2019 at 8:54
  • Please refer stackoverflow.com/questions/1225146/… new FileWriter(UserData, true); Commented Apr 22, 2019 at 9:00
  • I have tested you code and it write corretly a text file. You must sure that your file path is correct! Commented Apr 22, 2019 at 9:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.