【问题标题】:Cleaner way to clear a text file's contents清除文本文件内容的更简洁方法
【发布时间】:2015-04-03 04:31:33
【问题描述】:

我有这个网络浏览器应用程序,我将浏览历史记录存储在用户 SD 卡中的 .txt 文件中。我清除历史记录的方式只是删除文件,如果文件不存在再次清除历史记录,我会抛出异常(此异常是临时的,因为我计划将来删除它,但在那里用于测试目的)。有没有办法在不删除更干净的文件的情况下清除 history.txt?这是我如何“清除”文件的代码 sn-p:

 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.");
    }

【问题讨论】:

  • 你所说的“清晰”是什么意思?清空它的内容?
  • 是的,我的坏话本可以更好的措辞。
  • 另外,我相信像 MainActivity.file 这样的静态变量即使在你的情况下也是一个非常糟糕的做法。
  • @Rocel 它没有破坏任何东西,所以嗯

标签: java android io


【解决方案1】:

你可以在this post 上做类似的事情:用空白 ("") 重写内容:

(我会在这里复制原帖:)

覆盖文件 foo.log:

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】:

    试试这个:

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

    当然,还有更简洁的方法来处理路径和文件名,但你会明白的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 2011-02-11
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多