回滚或重置bufferedwriter

gkn4icbw  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(468)

处理对文件写操作回滚的逻辑是否可能?
据我所知,bufferwriter只在调用.close()或.flush()时写入。
我想知道有没有可能,回滚写入或撤消任何更改的文件时,一个错误已经发生?这意味着bufferwriter充当临时存储器来存储对文件所做的更改。

p4tfgftt

p4tfgftt1#

你写的东西有多大?如果不是太大,那么可以写入bytearrayoutputstream,这样就可以在内存中写入,而不会影响要写入的最终文件。只有当您将所有内容写入内存并执行了所有要执行的操作以验证所有内容都正常后,才能写入输出文件。几乎可以保证,如果文件被写入,它将被完整地写入(除非磁盘空间用完)。举个例子:

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

如果您必须(或只想)使用writer而不是outputstreams,下面是一个等效的示例:

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();
}
qvk1mo1f

qvk1mo1f2#

不可能回滚或撤消已应用于文件/流的更改,但有很多替代方法:
一个简单的技巧是清除目标并再次重做进程,以清除文件:

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

您可以完全删除内容,然后重新运行。
或者,如果您确定最后一行是问题所在,则可以执行“删除最后一行”操作,例如回滚该行:
删除文本文件中的最后一行

相关问题