How can I append an existing file in Java?
Appending data to a file is a fairly common task. You'll be surprised to know that there was no support for file appending in JDK1.02, and developers supporting that platform are forced to re-write the entire file to a temporary file, and then overwrite the original. As most users support either JDK1.1 or the Java 2 platform, you'll probably be able to use the following FileOutputStream constructor to append data:
public FileOutputStream(String name, boolean append) throws FileNotFoundException
name
- the system-dependent file name
append
- if true
, then bytes will be written to
the end of the file rather than the beginningFor example, to append the file 'autoexec.bat' to add a new path statement on a Wintel machine, you could do the following:
FileOutputStream appendedFile = new FileOutputStream ("c:\\autoexec.bat", true);