I am using this to save a string value to a file:
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(content);
writer.close();
If the file exists, I get an error.
I am using this to save a string value to a file:
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(content);
writer.close();
If the file exists, I get an error.
File file = new java.io.File(path);
if (file.exists()) {
//create writer and write to it here
}
Edit: Think the question was phrased differently before, or I read it wrong
I'm assuming you're getting an IOException on the first line (you don't actually say what error you get).
You shouldn't get an exception unless the filename refers to a directory or the file cannot be written to for some reason (probably permissions).
First thing to do is check that the file path is correct and that your user has write permission on the file.
Probably you've a problem of permissions or something like that, because your code seems correct. Other solution could be delete the file if it exists and then create the new one, but is very probable that if you cannot overwrite the file, you cannot delete it too.
According to Sun's documentation, the FileWriter(String)
constructor:
FileWriter
public FileWriter(String fileName) throws IOException
Constructs a FileWriter object given a file name.
Parameters
fileName
-String
The system-dependent filename.Throws
IOException
- if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
What you're dong looks correct. What Java are you using?