问题
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(" ");
}
}
回答1:
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
回答2:
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
回答3:
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);
回答4:
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
来源:https://stackoverflow.com/questions/29878237/java-how-to-clear-a-text-file-without-deleting-it