Overwriting files in java code


















Collectives on Stack Overflow. Learn more. Asked 7 years, 10 months ago. Active 7 years, 10 months ago. Viewed 4k times. Aarish Ramesh Aarish Ramesh 5, 13 13 gold badges 52 52 silver badges 99 99 bronze badges. Do you have any evidence that this is actually causing a bottleneck in your code? Why can't you store the data in a temporary buffer and replace the contents whenever needed and write it at the completion?

JonSkeet: No evidence but creating large number of objects generally is seen as a overhead in java right! ManuViswam: ya i thought about it and i might adopt it. But if i go with the above way, can't it be done without creating FileWriter for each write?

Do you really think object creation is going to be the bottleneck? Don't guess about performance - measure it. Show 7 more comments. Active Oldest Votes. Not a direct answer, but anyway. You not only lose your original file, but also the new file contents The important thing here isn't what you do.

It's what you don't do. I'll explain what I mean. You note that it has three parameters: the Path the byte array OpenOption options You may have noticed also that OpenOption is followed by an ellipsis. What you may not know is that the ellipsis doesn't mean 1-to-many. It means 0-to-many. And that's precisely what you'll do if you want to overwrite the file.

Community Bot 1 1 1 silver badge. Paul Samsotha Paul Samsotha k 33 33 gold badges silver badges bronze badges. Why not simply delete and create new? Aniket Thakur Aniket Thakur Your question is a bit misleading. When you say overwriting a file it generally means staring to write from beginning of the file and removing if any text already exists. For that you code will just work fine reference. Now if you want to append to the existing file then you can use append function of PrintWriter class.

That looked like an immediate answer to your question. But print function of PrintWriter does overwrite the content. That explains why your original content gets erased. As mentioned in previous comment if you wish to retain original content use append. The Overflow Blog. Podcast Making Agile work for data science. Stack Gives Back Featured on Meta. New post summary designs on greatest hits now, everywhere else eventually.



0コメント

  • 1000 / 1000