有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Cleaner清除文本文件内容的方法

我有一个web浏览器应用程序,我将浏览历史记录存储在一个文件夹中。用户SD卡中的txt文件。清除历史记录的方法就是删除该文件,如果该文件不存在,则再次清除历史记录时,我会抛出一个异常(此异常是临时的,因为我计划将来删除它,但出于测试目的而存在)。有没有办法澄清历史。txt而不删除更干净的文件?下面是我如何“清除”文件的代码片段:

 if(MainActivity.file.exists()){
        MainActivity.file.delete();
        for(int x = 0; x < 1000; x++){
            urls[x] = "";
        }
        adap.notifyDataSetChanged();}
else if(!MainActivity.file.exists()){
        throw new InvalidFileDeletionException("File does not exist and therefore can not be deleted.");
    }

共 (2) 个答案

  1. # 1 楼答案

    您可以像在this post上那样:用空格(“”)重写内容:

    (我将在这里复制原始帖子:)

    覆盖文件foo。日志:

    File myFoo = new File("path/to/history.txt");
    FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
                                                                     // false to overwrite.
    byte[] myBytes = "".getBytes() 
    fooStream.write(myBytes);
    fooStream.close();
    

    File myFoo = new File("path/to/history.txt");
    FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
                                                         // false to overwrite.
    fooWriter.write("");
    fooWriter.close();
    
  2. # 2 楼答案

    试试这个:

    FileWriter fw = new FileWriter(path + "/history.txt", false);
    fw.close();
    

    当然,有更简洁的方法来处理路径和文件名,但你可以理解