javaspringbufferedwriteritemwriter

Rollback or Reset a BufferedWriter


A logic that handles the rollback of a write to a file is this possible?

From my understanding a BufferWriter only writes when a .close() or .flush() is invoked.

I would like to know is it possible to, rollback a write or undo any changes to a file when an error has occurred? This means that the BufferWriter acts as a temporary storage to store the changes done to a file.


Solution

  • How big is what you're writing? If it isn't too big, then you could write to a ByteArrayOutputStream so you're writing in memory and not affecting the final file you want to write to. Only once you've written everything to memory and have done whatever you want to do to verify that everything is OK can you write to the output file. You can pretty much be guaranteed that if the file gets written to at all, it will get written to in its entirety (unless you run out of disk space.). Here's an example:

    import java.io.*;    
    
    class Solution {
    
        public static void main(String[] args) {
    
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
    
                // Do whatever writing you want to do here.  If this fails, you were only writing to memory and so
                // haven't affected the disk in any way.
                os.write("abcdefg\n".getBytes());
    
                // Possibly check here to make sure everything went OK
    
                // All is well, so write the output file.  This should never fail unless you're out of disk space
                // or you don't have permission to write to the specified location.
                try (OutputStream os2 = new FileOutputStream("/tmp/blah")) {
                    os2.write(os.toByteArray());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    If you have to (or just want to) use Writers instead of OutputStreams, here's the equivalent example:

    Writer writer = new StringWriter();
    try {
    
        // again, this represents the writing process that you worry might fail...
        writer.write("abcdefg\n");
    
        try (Writer os2 = new FileWriter("/tmp/blah2")) {
            os2.write(writer.toString());
        }
    
    } catch (IOException e) {
        e.printStackTrace();
    }