繁体   English   中英

如何覆盖现有的.txt 文件

[英]How to overwrite an existing .txt file

我有一个创建 a.txt 文件的应用程序。 我想覆盖它。 这是我的 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();
}

如果文件存在,我应该在 else 子句中放入什么,以便可以覆盖它?

你不需要在else子句中做任何特别的事情。 您实际上可以使用具有两种不同模式的Writer打开文件:

  • 默认模式,覆盖整个文件
  • append mode(在构造函数中由boolean设置为true ),它将新数据附加到现有数据

只需在你的else块中调用file.delete() 这应该删除该文件,如果这是你想要的。

您不需要执行任何操作,默认行为是覆盖。

不知道为什么我被投票,严重...这段代码将始终覆盖文件

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)

在给定文件名的情况下构造FileWriter对象,该文件名带有一个布尔值,指示是否附加写入的数据。

下面一行代码将帮助我们将文件清空。

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

下面的代码将帮助我们删除该文件。

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

        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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