How do I check if a file exists and if it does, delete it and write a new one?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Mark_Shearman
Posted On:   Friday, March 8, 2002 04:15 AM

I am using File, FileWriter and PrintWriter to write Strings to a simple txt file...


Mark

Re: How do I check if a file exists and if it does, delete it and write a new one?

Posted By:   Christopher_Schultz  
Posted On:   Friday, March 8, 2002 05:19 AM

If you create a new FileWriter for a particular file, and don't set the 'append' flag, then you will overwrite any file that was there.



Why worry about if you are clobbering a file?



-chris

Re: How do I check if a file exists and if it does, delete it and write a new one?

Posted By:   Mark_Shearman  
Posted On:   Friday, March 8, 2002 04:28 AM

I should also say that I have tried to use exists() in this way:



(private member data) File file = new File(path);

------------------



if (file.exists()) {
file.delete();
}
file = new File(path);
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw, true);

etc.

...and note that in my real code I have a try/catch block for the FileWriter constructor... just omitted it above for quickness.

The result of the above code is to append the new data to the end of the old file which should have been deleted! Grrr...

Mark

About | Sitemap | Contact