Author Topic: Append an existing file in Java  (Read 29778 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
Append an existing file in Java
« on: May 19, 2009, 12:48:00 PM »
Question
How can I append an existing file in Java?

Answer
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
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning
For 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);