5

I have an application that creates a .txt file. I want to overwrite it. This is my function:

try{
    String test = "Test string !";
    File file = new File("src\\homeautomation\\data\\RoomData.txt");

    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }else{

    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(test);
    bw.close();

    System.out.println("Done");
}catch(IOException e){
    e.printStackTrace();
}

What should I put in the else clause, if the file exists, so it can be overwritten?

Christian Neverdal
  • 5,655
  • 6
  • 38
  • 93
mirzak
  • 1,043
  • 4
  • 15
  • 30
  • 1
    Possible duplicate of [Overwriting txt file in java](http://stackoverflow.com/questions/13729625/overwriting-txt-file-in-java) – Galabyca Mar 08 '16 at 15:25

4 Answers4

9

You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :

  • default mode, which overwrites the whole file
  • append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
Dici
  • 25,226
  • 7
  • 41
  • 82
  • 1
    "You don't need to do anything particular in the else clause"... Actually you mean, he shouldn't have an if clause too. Just trying to come up with some smart comment myself :) – peter.petrov Nov 06 '14 at 17:19
  • I thought that `createNewFile` would create all the non-existing parent directories of the file, but after taking a look at the doc, it doesn't (`File.mkdirs()` do). So yes, the if clause is unnecessary here – Dici Nov 06 '14 at 17:32
6

You don't need to do anything, the default behavior is to overwrite.

No clue why I was downvoted, seriously... this code will always overwrite the file

try{
        String test = "Test string !";
        File file = new File("output.txt");

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(test);
        bw.close();

        System.out.println("Done");
    }catch(IOException e){
        e.printStackTrace();
    }
zmf
  • 9,095
  • 2
  • 26
  • 28
2

Just call file.delete() in your else block. That should delete the file, if that's what you want.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • 1
    He does not want to delete the file, he wants to overwrite it. He's talking about deletion because he does not know how a `Writer` works and think he need to delete the file to overwrite it – Dici Nov 06 '14 at 17:15
  • He can delete it, then do the same as in the case where it doesn't exist. That's why I put "if that's what you want", I wasn't quite sure what he wants. – peter.petrov Nov 06 '14 at 17:15
  • Then why even deleting it, since he will obtain the same result without doing so ? – Dici Nov 06 '14 at 17:16
  • @Dici Right, that's smart indeed. I wouldn't have figured it out. – peter.petrov Nov 06 '14 at 17:17
0
FileWriter(String fileName, boolean append)

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

The Below one line code will help us to make the file empty.

FileUtils.write(new File("/your/file/path"), "")

The Below code will help us to delete the file .

try{

            File file = new File("src\\homeautomation\\data\\RoomData.txt");

            if(file.delete()){
                System.out.println(file.getName() + " is deleted!");
            }else{
                System.out.println("Delete operation is failed.");
            }

        }catch(Exception e){

            e.printStackTrace();

        }