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();
}
2条答案
按热度按时间p4tfgftt1#
你写的东西有多大?如果不是太大,那么可以写入bytearrayoutputstream,这样就可以在内存中写入,而不会影响要写入的最终文件。只有当您将所有内容写入内存并执行了所有要执行的操作以验证所有内容都正常后,才能写入输出文件。几乎可以保证,如果文件被写入,它将被完整地写入(除非磁盘空间用完)。举个例子:
如果您必须(或只想)使用writer而不是outputstreams,下面是一个等效的示例:
qvk1mo1f2#
不可能回滚或撤消已应用于文件/流的更改,但有很多替代方法:
一个简单的技巧是清除目标并再次重做进程,以清除文件:
您可以完全删除内容,然后重新运行。
或者,如果您确定最后一行是问题所在,则可以执行“删除最后一行”操作,例如回滚该行:
删除文本文件中的最后一行