我制作的函数有一点问题。 我希望每次我给这个函数一个字符串,它都会将我保存到同一文件中的新行,但实际上现在只保存我给出的最后一个字符串。这就像一次又一次的覆盖,需要一些帮助
public void WritingGZFile(String directory, String linesWithPattern, String newFile) throws IOException
{
newFile = directory + '\\' + newFile;
BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(
newFile)));
out.write(linesWithPattern.getBytes());
out.write("\r\n".getBytes());
out.close();
}
例如,在 BufferedWriter 中有一个名为 newLine 的方法可以帮助做到这一点。
但是因为我想使用 GZIPOutputStream 类,所以我需要 BufferedOutputStream。
有什么办法吗?感谢ypu
最佳答案
你说得对,你覆盖了文件。如果您使用 FileOutputStream 打开它,它将从头开始。您可以保持流打开或使用 append mode通过在文件(名称)后指定 true
。
BufferedOutputStream out = new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream(newFile, true)
)
);
使用 GZIPOutputStream,如果您在每行上打开一个新流,则会产生相当大的开销,但它被定义为以这种方式工作。 (再次强调:保持其打开状态也有帮助)。
关于java - BufferedOutputStream 多行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243654/