5

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(" ");
    }
} 
braX
  • 11,506
  • 5
  • 20
  • 33
Kemosabe
  • 311
  • 2
  • 4
  • 16

7 Answers7

13

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

The Coder
  • 3,447
  • 7
  • 46
  • 81
  • Thanks for this.. It helped me resolve an issue with trailing string from previous file contents. – Adi B Oct 24 '19 at 08:02
7

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);
Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
  • `File.createNewFile()` creates a new file, not what was asked for. Ditto `new PrintWriter(...)`. `writer.print("")` does nothing and should be omitted. – user207421 Aug 10 '23 at 06:35
6

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

Ankur Anand
  • 3,873
  • 2
  • 23
  • 44
1

You can just print an empty string into the file.

PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
1218985
  • 7,531
  • 2
  • 25
  • 31
  • `print("")` does nothing and can be omitted. This works only because `new PrintWriter(...)` creates a new file, which is not what was asked for. – user207421 Aug 10 '23 at 06:06
0

type

new PrintWriter(PATH_FILE).close();
StreamsGit
  • 91
  • 1
  • 7
-1

Better to use this:

    public static void clear(String filename) throws IOException {
    FileWriter fwOb = new FileWriter(filename, false); 
    PrintWriter pwOb = new PrintWriter(fwOb, false);
    pwOb.flush();
    pwOb.close();
    fwOb.close();
}
-1

I had the same problem. Using class FileWriter worked for me.

import java.io.File;
import java.io.IOException; 

FileWriter myWriter = new FileWriter("src\\LoginInformationList.txt");
ArrayList<String> loginInfo = LInfo.passLoginInformation();
for (String line: loginInfo){
    myWriter.write(line);
}
myWriter.close();

The above cleared the text file and wrote my login information.

w3schools guide: https://www.w3schools.com/java/java_files_create.asp

Abra
  • 19,142
  • 7
  • 29
  • 41
  • Creates a new file, and not an empty one. Doesn't answer the question in any way. – user207421 Aug 10 '23 at 06:08
  • I believe the method above creates a new file named src\\LoginInformationList.txt. Since this file already exists at this location, it replaces the old file with a new one that is empty. The end result is an empty file with the same name, same location, and same path name. It does not clear the original file, but the result should be similar – Brennen Le Aug 24 '23 at 17:01