How to overwrite a file in Java
Can we overwrite a file using Java? Yes! In this blog, you will learn how to overwrite a file in Java using java.io.FileWriter class.
Class FileWriter
This class belongs to java.io package this class is used to write a character into the file. We can create or overwrite a file using java.io.FileWriter class.
Declaration
public class FileWriter extends OutputStreamWriter
Constructors
FileWriter(File file)FileWriter(File file, boolean append)FileWriter(FileDescriptor fd)FileWriter(String fileName)FileWriter(String fileName, boolean append)
Code with explanation for overwriting a file in Java
Here we overwrite a .txt file using java.io.FileWriter class.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class OverwriteFile {
public static void main(String[] args) {
Scanner scObj = new Scanner(System.in);
System.out.println("Input the contents of the file."
+ "\n===================================");
String content = scObj.nextLine();
scObj.close();
try {
FileWriter writerObj = new FileWriter("F:\\WorkFile.txt", false);
writerObj.write(content);
writerObj.close();
System.out.println("================================\n"
+ "File successfully overwritten.");
} catch (IOException e) {
e.printStackTrace();
}
}
}Output Input the contents of the file. =================================== hello, you are viewing a java blog on codespeedy website ================================ File successfully overwritten.
Also, you can see Workfile.txt
Explanation
- Line 8 – 12: In this code, we created an object named scObj of Scanner class to read input and store in the String content variable using scObj.nextLine() method.
- Line 14 – 16: Here in try block we created an object named writerObj of FileWriter class and also we pass the File Location value in a string and a false Boolean value in the FileWriter parameter constructor. Now using writerObj.write(content) we write the string data in the WorkFile.txt.
- The reason why we pass the false boolean value? If you want to overwrite a file, you must pass the false boolean value and to append in file, you must pass the true boolean value in the parameter of FileWriter() class.
- Line 21 – 23: Here we catch the exception which may be thrown by FileWriter class.
Also read: Reading and writing a file in java using FileWriter and FileReader
That’s enough for a how to overwrite a file in Java.
Thank you

Leave a Reply