hi,
how do you check if a file exist before you write to it?
I have a registration page which creates a txt file named the username
the user chooses
once registration is complete
Now i don't want user to be overwritten so how do i check if the file
already exists first before writing?
thanks
-morc
morc - 07 Feb 2006 17:07 GMT
i forgot to mention i am using FileWriter
Joe Attardi - 07 Feb 2006 17:22 GMT
> hi,
> how do you check if a file exist before you write to it?
Before creating your FileWriter, you can create a new File object
around the file you want to check, then call the exists() method on it.
File txtFile = new File("myfile.txt");
if (txtFile.exists()) { ... } // the file already exists
else { ... } // the file does not exist
Hope this helps..

Signature
Joe Attardi
Gordon Beaton - 07 Feb 2006 17:28 GMT
> File txtFile = new File("myfile.txt");
> if (txtFile.exists()) { ... } // the file already exists
> else { ... } // the file does not exist
In the interest of avoiding a race condition, this is a better
mechanism since File.create() tests and creates the file atomically,
and only if the file doesn't already exist:
File txtFile = new File("myfile.txt");
if (txtFile.createNewFile()) {
// a new file was created
}
else {
// the file already existed
}
/gordon

Signature
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Joe Attardi - 07 Feb 2006 17:31 GMT
> In the interest of avoiding a race condition, this is a better
> mechanism since File.create() tests and creates the file atomically,
> and only if the file doesn't already exist:
Good call, Gordon. Shame on me for missing this one...
morc - 07 Feb 2006 17:43 GMT
Thomas Fritsch - 07 Feb 2006 17:26 GMT
> how do you check if a file exist before you write to it?
String fileName = ...;
File file = new File(fileName);
if (file.exists())
...do something
else
...do something else

Signature
"Thomas:Fritsch@ops.de".replace(':', '.').replace('@', '$')
Roedy Green - 08 Feb 2006 23:17 GMT
>how do you check if a file exist before you write to it?
see File.exists http://mindprod.com/jgloss/file.html

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.