To overwrite a file in Java, set the second argument of
FileWriter
to false
.For example, this is how you can overwrite somefile.txt
file in the /Users/whaadev
directory with Hello World!
:
try {
FileWriter writer = new FileWriter("/Users/whaadev/somefile.txt", false);
writer.write("Hello World!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}