javafileformatter

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

Solution

  • 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