tags:

views:

137

answers:

4

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.

A: 
 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

lucas
How does that answer the question?
waxwing
+1  A: 

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.

Dan Dyer
A: 

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.

HED
+2  A: 

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?

Chip Uni
Seriously, mrblah, what's the point of marking this -- or any other -- as the correct answer without ever explaining what it is you were doing wrong, or answering any of the questions people asked of you in the comments to your question? It's not helpful to anyone, and again, it's incredibly disrespectful of the time people are giving you.
delfuego
the error was not related to me creating a file, it was my mistake thanks!
mrblah