回滚或重置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("abcdefgn".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("abcdefgn");
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();

您可以完全删除内容,然后重新运行。

或者,如果你确定最后一行是问题所在,你可以出于自己的目的删除最后一行的操作,比如回滚行:

删除文本文件中的最后一行

最新更新