9

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.

4

3 回答 3

30

如果是这样,我想知道如何附加到文件而不是覆盖。

这很容易 - 你甚至不需要DataOutputStream. 很好FileOutputStream,使用带有append参数的构造函数:

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

或者使用 Java 7 的try-with-resources

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

如果出于某种原因确实需要DataOutputStream,您可以FileOutputStream以相同的方式包装打开的。

于 2013-06-04T20:54:59.500 回答
3
Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);

这是用于字节追加。不要忘记异常

于 2015-11-10T14:32:52.087 回答
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();

当然,把它放在 try - catch 块中。

于 2013-06-04T20:57:31.550 回答