Overwrite a File in Java

Sheeraz Gul May 27, 2022
Overwrite a File in Java

This tutorial demonstrates how to overwrite a file in Java.

Overwrite a File in Java

Overwriting a text file is an easy operation in Java. Follow the step-by-step process below.

  • First of all, delete the file you want to overwrite.
  • Create a new file with the same name.
  • Now, write the new content in the new file using FileWriter.

Let’s try an example:

package delftstack;

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

public class Overwrite_File {
	public static void main(String[] args) {
        File Old_File=new File("delftstack.txt");
        Old_File.delete();
        File New_File=new File("delftstack.txt");
        String Overwritten_Content = "Hello, This is a new text file from delftstack.com after overwriting the previous file.";
        System.out.println(Overwritten_Content);

        try {
            FileWriter Overwritten_File = new FileWriter(New_File, false);
            Overwritten_File.write(Overwritten_Content);
            Overwritten_File.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The code above will overwrite a file in Java. The previous file has the text:

Hello, This is a text file from delftstack.com before overwriting the file.

File Before Overwrite

After running the code, the output will be the following.

Hello, This is a new text file from delftstack.com after overwriting the previous file.

File After Overwrite

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook