Share on Google+Share on Google+

Java file overwrite

Advertisement
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.

Advertisements

Posted on: June 5, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.