清除文本文件内容的更简洁方法
Cleaner way to clear a text file's contents
我有这个网络浏览器应用程序,我将浏览历史记录存储在用户 SD 卡中的 .txt 文件中。我清除历史记录的方法就是删除文件,如果文件不存在,如果再次清除历史记录,我会抛出异常(这个异常是暂时的,因为我打算以后删除它,但是在那里用于测试目的)。有没有办法在不删除更干净的文件的情况下清除 history.txt?这是我如何处理 "clearing" 文件的代码片段:
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.");
}
您可以像 this post 那样做:用空白 ("") 重写内容:
(我将在此处复制原始 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();
试试这个:
FileWriter fw = new FileWriter(path + "/history.txt", false);
fw.close();
当然,还有更简洁的方法来处理路径和文件名,但您明白了。
我有这个网络浏览器应用程序,我将浏览历史记录存储在用户 SD 卡中的 .txt 文件中。我清除历史记录的方法就是删除文件,如果文件不存在,如果再次清除历史记录,我会抛出异常(这个异常是暂时的,因为我打算以后删除它,但是在那里用于测试目的)。有没有办法在不删除更干净的文件的情况下清除 history.txt?这是我如何处理 "clearing" 文件的代码片段:
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.");
}
您可以像 this post 那样做:用空白 ("") 重写内容:
(我将在此处复制原始 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();
试试这个:
FileWriter fw = new FileWriter(path + "/history.txt", false);
fw.close();
当然,还有更简洁的方法来处理路径和文件名,但您明白了。