11

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.

john stamos
  • 1,054
  • 5
  • 17
  • 36

3 Answers3

35

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4
Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);

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

Lewik
  • 649
  • 1
  • 6
  • 19
  • 3
    Welcome to SO, and thanks for proving an answer. This is up for review in the low quality posts queue because it is a code only answer, and we don't really like those. If you want to join in, then you are welcome, but you have to put a little more effort into your answers. We expect code to be surrounded by an explanation of how it solves the OP's problem. If you like, you can read [ask] and [answer] to clear things up a bit. Ty for your time. – Software Engineer Nov 10 '15 at 21:26
  • 1
    Files.write(Paths.get("/var/error.txt"), byteArray, StandardOpenOption.APPEND); Use this snippet – ThinkTank Mar 11 '19 at 11:06
1
File file =new File("your-file");
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(your-string);
bufferWritter.close();

Of coruse put this in try - catch block.

Marcin_cyna
  • 97
  • 1
  • 1
  • 6