简体   繁体   English

使用BufferedWriter将相同的数据写入多个文件

[英]use BufferedWriter to write same data to multiple files

I'm interested in writing some data I'm receiving into two different files (same data). 我有兴趣将我收到的一些数据写入两个不同的文件(相同的数据)。

In my code, I'm using BufferedWriter and FileWriter to write the data to files, and I want, as a backup, to write the same data on the local storage and on the SD card. 在我的代码中,我使用BufferedWriterFileWriter将数据写入文件,我希望,作为备份,在本地存储和SD卡上写入相同的数据。

My question is if I need to implement this with 2 FileWriters and 2 BufferedWriters , or is there a way to use the same BufferedWriter for both files? 我的问题是,如果我需要用2个FileWriters和2个BufferedWriters来实现它,还是有办法对两个文件使用相同的BufferedWriter

Is there a more efficient way to implement this task? 有没有更有效的方法来实现这项任务?

Reusing the same writer isn't possible - unless you spend the time to implement your own special subclass of Writer that writes its output into multiple files at the same point in time. 重用同一个编写器是不可能的 - 除非你花时间实现自己的Writer特殊子类,它在同一时间点将其输出写入多个文件。 (to then pass an instance of such a CopyingWriter to the ctor of BufferedWriter). (然后将这样一个CopyingWriter的实例传递给BufferedWriter的ctor )。

But I suggest to not do that. 但我建议这样做。 Instead: write the file once . 相反:写一次文件。 Then use other, existing technology to copy the output file. 然后使用其他现有技术来复制输出文件。

Always aim for simplicity. 始终瞄准简单。 You intend to create a very special solution, where one writer writes to n files. 您打算创建一个非常特殊的解决方案,其中一个编写器写入n个文件。 But there is no need to do that. 但没有必要这样做。 Write your file once, then copy it n times. 写一次你的文件,然后复制n次。 This approach doesn't require "innovation" - you just need to use what already exists (see here for example). 这种方法不需要“创新” - 你只需要使用已经存在的东西(例如见这里 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM