0

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)                 
{   
    try
    {
        PrintWriter printWriter = new PrintWriter (file);
        printWriter.print(cnvrt);
        printWriter.close ();           
    }
    catch(Exception exception)
    {
        exception.printStackTrace();
    }
}

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 FileWriter and BufferedReader, I obtained the empty file. Can somebody explain me this behavior?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3002538
  • 15
  • 1
  • 1
  • 5
  • First read the content, do your changes and store it in some variables, close your file, now open your file in write mode and paste the contents of variables in that file. – AJ. Nov 20 '13 at 06:53
  • I'm confused. Do you want to overwrite the existing content, or do you want to append to the existing content? – isnot2bad Nov 20 '13 at 07:06

3 Answers3

0

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

see http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.File)

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.

Update

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.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

There's two ways I can think of if you want to overwrite the file with changed/altered/updated information in the file

1) Use a StringBuilder to append each desired/changed line, then print the StringBuilder#toString() to the file. This overwrite the file with updated info

2) Write each desired/changed line to a temp file, then rename the temp file back to the old file name. See this Answer

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
-1

Why not simply delete and create new?

public static void txtFile(String cnvrt, File file)
{
    PrintWriter printWriter = null;
    String filepath = file.getAbsolutePath();
    try {
        if(file.exists()){
            file.delete();
        }
        printWriter = new PrintWriter(new File(filepath));
        printWriter.print(cnvrt);
        printWriter.close ();
    } catch (FileNotFoundException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
}

Note : It is not a good programming practice to catch RuntimeException unless you intent to do something with it.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • yes i was doing the same way before but i know it is not a good way to do it – user3002538 Nov 20 '13 at 06:58
  • Your question is a bit misleading. When you say overwriting a file it generally means staring to write from beginning of the file and removing if any text already exists. For that you code will just work fine [reference](http://stackoverflow.com/questions/6994518/how-to-delete-the-content-of-text-file-without-deleting-itself) . Now if you want to append to the existing file then you can use append() function of PrintWriter class. – Aniket Thakur Nov 20 '13 at 07:16
  • so, as the code should work just fine, why go to the bother of deleting the file? – Scary Wombat Nov 20 '13 at 07:32
  • That looked like an immediate answer to your question. But print() function of PrintWriter does overwrite the content.That explains why your original content gets erased. As mentioned in previous comment if you wish to retain original content use append(). – Aniket Thakur Nov 20 '13 at 08:30