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

依然范特西╮ 提交于 2019-12-06 05:16:43

问题


I am wondering what the best way to clear a file is. I know that java automatically creates a file with

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

if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank? Here is what I was thinking:

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

回答1:


If you want to clear the file without deleting may be you can workaround this

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

Edit: It throws exception so need to catch the exceptions




回答2:


Best I could think of is :

Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);

and

Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);

In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.

Hope it Helps




回答3:


You could delete the file and create it again instead of doing a lot of io.

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

Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :

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

Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :

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



回答4:


You can just print an empty string into the file.

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


来源:https://stackoverflow.com/questions/29878237/java-how-to-clear-a-text-file-without-deleting-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!