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

隐身守侯 提交于 2019-12-04 12:56:28

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

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

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);

You can just print an empty string into the file.

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