Rollback or Reset a BufferedWriter

859 Views Asked by At

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.

2

There are 2 best solutions below

1
CryptoFool On BEST ANSWER

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();
}
0
PSo On

It is impossible to rollback or undo changes already applied to files/streams, but there are tons of alternatives to do so:

One simple trick is to clean the destination and redo the process again, to clean the file:

PrintWriter writer = new PrintWriter(FILE_PATH);
writer.print("");
// other operations
writer.close();

You can remove the content entirely and re-run again.

Or if you are sure the last line(s) are the problems, you may do remove last line actions for your purpose, such as rollback the line instead:

Delete last line in text file