问题描述
处理文件写入回滚的逻辑是否可行?
据我所知,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();
您可以完全删除内容并重新运行。
或者,如果您确定最后一行是问题,您可以出于您的目的删除最后一行操作,例如回滚该行: