Java - 如何清除文本文件而不删除它?

Java - How to Clear a text file without deleting it?

我想知道清除文件的最佳方法是什么。我知道 java 会自动创建一个包含

的文件
f = new Formatter("jibberish.txt");  
s = new Scanner("jibberish.txt");

如果 none 已经存在。但是,如果存在并且我想在每次 运行 程序时清除它怎么办?这就是我想知道的:再说一遍我如何清除一个已经存在的文件只是空白? 这就是我的想法:

public void clearFile(){
    //go through and do this every time in order to delete previous crap
    while(s.hasNext()){
        f.format(" ");
    }
} 

您可以删除文件并重新创建它,而不用做大量的 io.

if(file.delete()){
    file.createNewFile();
}else{
    //throw an exception indicating that the file could not be cleared
}

或者,您可以按照其他答案中的说明一次性覆盖文件的内容:

PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();

此外,您正在使用来自 Scanner 的构造函数,它接受一个 String 参数。此构造函数不会从文件中读取,而是使用 String 参数作为要扫描的文本。您应该首先创建一个文件句柄,然后将其传递给 Scanner 构造函数:

File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);

如果您想在不删除的情况下清除文件,您可以解决此问题

public static void clearTheFile() {
        FileWriter fwOb = new FileWriter("FileName", false); 
        PrintWriter pwOb = new PrintWriter(fwOb, false);
        pwOb.flush();
        pwOb.close();
        fwOb.close();
    }

编辑:它抛出异常所以需要捕获异常

您可以只在文件中打印一个空字符串。

PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();

我能想到的最好的是:

Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);

Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);

在这两种情况下,如果 pathObject 中指定的文件是可写的,那么该文件将被截断。无需调用 write() 函数。上面的代码足以 empty/truncate file.This is new in java 8.

希望对您有所帮助

类型

new PrintWriter(PATH_FILE).close();