在java中,如何在不删除文件的情况下清空文件内容?
占用了。这个怎么样:在java中,如何在不删除文件的情况下清空文件内容?,java,file,io,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
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
或者,这将创建新文件或覆盖现有文件:
File file = new File("myfile");
if(file.exists()){
file.delete();
}
file.createNewFile();
或@CandiedOrange的PrinterWriter:
Files.newBufferedWriter(Paths.get("myfile"));
否则,好的老办法是:
new PrintWriter("myfile").close();
首先,问题是什么?第二,你测试过你所指出的代码吗?我相信这是重复的:新的PrintWriter(“filepath.txt”).close()有什么问题代码>?没什么错,只是有上百万种方法:)我已经把你的建议加入到混合中了
File file = new File("myfile");
FileOutputStream fooStream = new FileOutputStream(file, false);
fooStream.write("".getBytes());
fooStream.close();