mirzak
mirzak

Reputation: 1047

How to overwrite an existing .txt file

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?

Upvotes: 5

Views: 27468

Answers (4)

zmf
zmf

Reputation: 9313

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();
    }

Upvotes: 7

Dici
Dici

Reputation: 25950

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

Upvotes: 9

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();

        }

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

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

Upvotes: 2

Related Questions