Reputation:
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();
}
}
Upvotes: 0
Views: 99
Reputation: 749
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
Upvotes: 2