Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending Byte[] to end of a binary file

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.

like image 817
john stamos Avatar asked Jun 04 '13 20:06

john stamos


2 Answers

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.

like image 94
Jon Skeet Avatar answered Oct 08 '22 02:10

Jon Skeet


Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);

This is for byte append. Don't forget about Exception

like image 44
Lewik Avatar answered Oct 08 '22 00:10

Lewik