user3002538 user3002538 - 7 months ago 18
Java Question

How to overwrite a file in java

In my program, I am trying to read the file and then trying to overwrite the file using txtFile method. f is the file which I am reading and doing operations on its contents and now want to replace its contents with the new string, s.

String s = obj1.method(string);
toFile(s, f);

my txtFile method is below:

public static void txtFile(String cnvrt, File file)
PrintWriter printWriter = new PrintWriter (file);
printWriter.close ();
catch(Exception exception)

While doing this way, my original content is erased and the file gets empty. Please suggest me how to overwrite the same file using printWriter class? Even when I am using the
, I obtained the empty file. Can somebody explain me this behavior?


Based upon your code and the API, it should work (OP wants to replace the contents).


file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.


Before calling PrintWriter printWriter = new PrintWriter (file); you should maybe to close the file first to ensure that there are no locks on the file.

Furthermore, unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.

So use printWriter.flush() to ensure the contents are flushed to disk.

Of course you should check to make sure that the contents that you are writing in valid and not null.