如何清空文件内容而不删除java中的文件?

时间:2016-07-17 20:57:42

标签: java file io

FileWriter fwriter = new FileWriter("C:/Users/NULL NULL NULL/Desktop/New Text Document.txt", false); // set the write to false so we dont append to it

BufferedWriter write = new BufferedWriter(fwriter); // this is the type so we can write to it.

write.write(""); // write empty string to delet everything

write.close(); // close the buffer to gain back memory space that the buffer 

接受了。

1 个答案:

答案 0 :(得分:5)

这个怎么样:

File file = new File("myfile");
if(file.exists()){
    file.delete();
}
file.createNewFile();

或者这将创建一个新文件或覆盖现有文件:

Files.newBufferedWriter(Paths.get("myfile"));

或@ CandiedOrange的PrinterWriter:

new PrintWriter("myfile").close();

否则,旧的方式:

File file = new File("myfile");
FileOutputStream fooStream = new FileOutputStream(file, false);

fooStream.write("".getBytes());
fooStream.close();