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

Kemosabe picture Kemosabe · Apr 26, 2015 · Viewed 56k times · Source

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(" ");
    }
} 

Answer

TheCoder picture TheCoder · Feb 16, 2017

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