Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an existing file in java

Tags:

java

file-io

I write this code to write data in a text file.

 Writer output = null;
   File file = new File("C:/HEADER.txt");
   output = new BufferedWriter(new FileWriter(file));
    output.write("hello");
    output.close();

I write this code to write over the file but what happened is that the data got deleted, and the only the new data appeared.

Writer output = null;
   File file = new File("C:/HEADER.txt");
   output = new BufferedWriter(new FileWriter(file));
    output.write("how are you");
    output.close();
like image 308
user2786306 Avatar asked Oct 30 '13 11:10

user2786306


People also ask

How do I edit an existing file in Java?

1) open the file for input 2) read the file 3) close the file 4) change the data in the file 5) open the file for output 6) write the changed data to the file 7) close the file Any book on Java will have the basics of Input and Output.

How do I add content to an existing file in Java?

In Java, we can append a string in an existing file using FileWriter which has an option to open a file in append mode. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in Java.

Does FileWriter overwrite existing file?

By default, the FileWriter writes to the beginning of the file (will overwrite existing data).


1 Answers

try

new FileWriter(file, true)

this will open the file in append mode

like image 158
upog Avatar answered Sep 24 '22 21:09

upog