javabufferedreaderfilewriter

Why does introducing a FileWriter delete all the content in the file?


I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.

File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));

String line = null;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.

File file = new File("new.txt");

FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));

String line = null;
while ((line = br.readLine()) != null) {
    System.out.println(line);
    fw.write(br.readLine().replaceAll("t", "1") + "\n");
}

Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)

fw.write(br.readLine().replaceAll("t", "1") + "\n");

Why is this occurring? am i following the correct approach to edit characters in a text file?

Or is there any other way of doing this?

Thank you.


Solution

  • public FileWriter(String fileName, boolean append)

    Parameters:

    fileName - String The system-dependent filename.

    append - boolean if true, then data will be written to the end of the file rather than the beginning.

    To append data use

    new FileWriter(file, true);