Java file overwrite


 

Java file overwrite

In this section, you will learn how to overwrite a file.

In this section, you will learn how to overwrite a file.

Java file overwrite

In this section, you will learn how to overwrite a file.

Overwriting cleans up all the data and then start writing the new content. You can overwrite the file also by using the output streams. As the FileOutputStream class consists of two parameters:

FileOutputStream (File file, boolean append)

So the constructor can be written as FileOutputStream ("myFile.txt", false). By setting the second parameter to 'false', the file will get overwritten every time. Otherwise, anything you write to that file will only be appended.

Here is the code:

import java.io.*;

public class FileOverwrite {
	public static void main(String[] args) throws Exception {
		String st = "Hello World";
		File file = new File("c:/data.txt");
		if (file.exists()) {
			FileOutputStream fos = new FileOutputStream(file, false);
			fos.write(st.getBytes());
			fos.close();
		}
	}
}

Through the above code, you can overwrite the file.

Ads