Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

Is this the best way to rewrite the content of a file in Java?

I want to rewrite the contents of a file.

What I have thought of so far is this:

  1. Save the file name
  2. Delete the existing file
  3. Create a new empty file with the same name
  4. Write the desired content to the empty file

Is this the best way? Or is there a more direct way, that is, not having to delete and create files, but simply change the content?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To overwrite file foo.log with FileOutputStream:

File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
                                                                 // false to overwrite.
byte[] myBytes = "New Contents
".getBytes(); 
fooStream.write(myBytes);
fooStream.close();

or with FileWriter :

File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
                                                     // false to overwrite.
fooWriter.write("New Contents
");
fooWriter.close();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...