Search code examples
javaandroidfilefilewriterbufferedwriter

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.

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?

Is there a more efficient way to implement this task?


Solution

  • 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. (to then pass an instance of such a CopyingWriter to the ctor of BufferedWriter).

    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. But there is no need to do that. Write your file once, then copy it n times. This approach doesn't require "innovation" - you just need to use what already exists (see here for example).