Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(" ");
    }
} 
like image 685
Kemosabe Avatar asked Apr 26 '15 13:04

Kemosabe


1 Answers

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

like image 130
Puspender Avatar answered Oct 05 '22 11:10

Puspender