微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

回滚或重置 BufferedWriter

如何解决回滚或重置 BufferedWriter

处理文件写入回滚的逻辑是否可行?

据我所知,BufferWriter 仅在调用 .close() 或 .flush() 时写入。

我想知道是否可以在发生错误时回滚写入或撤消对文件的任何更改? 这意味着 BufferWriter 充当临时存储器来存储对文件所做的更改。

解决方法

你写的东西有多大?如果它不是太大,那么您可以写入 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();
        }
    }
}

如果您必须(或只想)使用 Writers 而不是 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();
}
,

无法回滚或撤消已应用于文件/流的更改, 但是有很多替代方法可以这样做:

一个简单的技巧是清理目标并再次重做该过程,以清理文件:

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

您可以完全删除内容并重新运行。

或者,如果您确定最后一行是问题,您可以出于您的目的删除最后一行操作,例如回滚该行:

Delete last line in text file

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。