Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite an existing .txt file

Tags:

java

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?

like image 466
mirzak Avatar asked Nov 06 '14 17:11

mirzak


2 Answers

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
like image 123
Dici Avatar answered Sep 27 '22 18:09

Dici


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();
    }
like image 38
zmf Avatar answered Sep 27 '22 19:09

zmf