Java create a new file, or, override the existing file

Terence Lyu :

What I want to achieve is to create a file regardless of whether the file exists or not.

I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?

Or is there a clearer way of doing it?

Bruno Caceiro :

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true);  //appends to file

Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114973&siteId=1