✏️ Explanatory Question

[Operation on File]

Question:

What is the difference between the following two statements?

1. FileWriter fw = new FileWriter();

2. FileWriter fw = new FileWriter(, true);

👁 1 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Answer:

Statement 1:

FileWriter fw = new FileWriter();

This statement opens the file in overwrite mode.

  • If the file already contains data, the old data will be erased.
  • New data will be written from the beginning of the file.

Statement 2:

FileWriter fw = new FileWriter(, true);

This statement opens the file in append mode.

  • Existing data in the file remains unchanged.
  • New data is added at the end of the file.

Explanation:

The second parameter:

true

indicates:

Append Mode

If this parameter is absent, Java uses:

Overwrite Mode

Example:

Suppose the file contains:

Hello

Using Statement 1:

fw.write("Java");

Final file content:

Java

Old data is removed.

Using Statement 2:

fw.write("Java");

Final file content:

HelloJava

New data is appended at the end.


Conclusion:

  • FileWriter(file) → Overwrites existing data
  • FileWriter(file, true) → Appends new data