简体   繁体   中英

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?

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

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

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

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM