forcode
forcode

Reputation: 25

copying content of a file to the same file

Here i want to copy a content of a file and write it into same file

I have four lines in the text file and when i execute the following program I get blank text file

But br1.readLine reads a line and writes into the file by clearing the content in it, it has to write atleast one line and then while loop should end..

But i am getting a blank text file..!!!!

import java.io.*;

class ConsoleIo {
  public static void main(String args[]) 
    throws IOException,FileNotFoundException {
    System.out.println("hi");
    int a;
    char b;
    String c;
    BufferedReader br1;
    BufferedWriter br2;
    br1 = new BufferedReader(new FileReader(args[0]));
    br2 = new BufferedWriter(new FileWriter(args[0]));
    while ((c = br1.readLine()) != null) {
      br2.write(c);
    }
    br1.close();
    br2.close();
  }
}

Can anyone explain it please??

Upvotes: 1

Views: 235

Answers (2)

fge
fge

Reputation: 121730

The explanation: don't do that.

Text editors never do that for a reason.

First problem: you open a new FileWriter() over a file without the boolean argument; by default, this class will truncate the destination file.

Second problem: even if you did open the FileWriter in append mode, the behaviour of your FileReader in this case is undefined.

If you wrote this sample program to see how you could modify the contents of the file, remind that you must NOT take the "modify the contents of the file" stuff literally.

What you SHOULD do is:

  • create another temporary file in which you write the modified content;
  • ensure that the temporary file is "safe and sound";
  • atomically rename the temporary file to the original file.

If you fail to obey the scenario above, chances that your original file becomes corrupted in various ways are high.

Upvotes: 2

pL4Gu33
pL4Gu33

Reputation: 2085

You open a filereader and writer on the same (args[0]) element (same File).

Upvotes: 0

Related Questions