Appending Byte[] to end of a binary file

john stamos picture john stamos · Jun 4, 2013 · Viewed 24.3k times · Source

I'm parsing a file. I'm creating a new output file and will have to add the 'byte[] data' to it. From there I will need to append many many other 'byte[] data's to the end of the file. I'm thinking I'll get the user to add a command line parameter for the output file name as I already have them providing the file name which we are parsing. That being said if the file name is not yet created in the system I feel I should generate one.

Now, I have no idea how to do this. My program is currently using DataInputStream to get and parse the file. Can I use DataOutputStream to append? If so I'm wondering how I would append to the file and not overwrite.

Answer

Jon Skeet picture Jon Skeet · Jun 4, 2013

If so I'm wondering how I would append to the file and not overwrite.

That's easy - and you don't even need DataOutputStream. Just FileOutputStream is fine, using the constructor with an append parameter:

FileOutputStream output = new FileOutputStream("filename", true);
try {
   output.write(data);
} finally {
   output.close();
}

Or using Java 7's try-with-resources:

try (FileOutputStream output = new FileOutputStream("filename", true)) {
    output.write(data);
}

If you do need DataOutputStream for some reason, you can just wrap a FileOutputStream opened in the same way.