Wednesday, July 26, 2017

Overwriting vs. Appending the File in Java IO: FileOutputStream

Overwriting vs. Appending the File

When you create a FileOutputStream pointing to a file that already exists, you can decide if you want to overwrite the existing file, or if you want to append to the existing file. You decide that based on which of the FileOutputStream constructors you choose to use.
This constructor which takes just one parameter, the file name, will overwrite any existing file:

1
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt");

There is a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two examples:

1
2
3
4
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", true); 
//appends to file
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", false); 
//overwrites file 


@reference_1_tutorials.jenkov.com
Java IO: FileOutputStream

No comments:

Post a Comment