简体   繁体   English

以原子方式将byte []写入文件

[英]Atomically write byte[] to file

(This is a hypothetical question since it's very broad, and workarounds exist for specific cases.) (这是一个假想的问题,因为它涉及面很广,并且存在针对特定情况的解决方法。)

Is it possible to atomically write a byte[] to a file (as FileOutputStream or FileWriter ? 是否可以原子方式将byte[]写入文件(作为FileOutputStreamFileWriter

If writing fails, then it's unacceptable that part of the array is written. 如果写入失败,则写入部分数组是不可接受的。 For example, if the array is 1,000,000 bytes and the disk is full after 500,000 bytes, then no bytes should be written to the file, or the changes should somehow be rolled back. 例如,如果数组为1,000,000字节,而磁盘在500,000字节后已满,则不应将字节写入文件,或者应以某种方式回滚更改。 This should even be the case if a medium is physically disconnected mid-write. 如果介质在写入过程中物理断开连接,甚至应该是这种情况。

Assume that the maximum size of the array is known. 假定数组的最大大小是已知的。

Atomic writes to files are not possible. 无法对文件进行原子写入。 Operating systems don't support it, and since they don't, programming language libraries can't do it either. 操作系统不支持它,并且由于不支持,所以编程语言库也不能支持它。

The best you are going to get with a files in a conventional file system is atomic file renaming; 在传统文件系统中,使用文件获得的最好的结果就是原子文件重命名。 ie

  1. write new file into same file system as the old one 将新文件写入与旧文件相同的文件系统
  2. use FileDescriptor.sync() to ensure that new file is written 使用FileDescriptor.sync()确保写入新文件
  3. rename the new file over the old one; 将新文件重命名为旧文件; eg using 例如使用

      java.nio.file.Files.move(Path source, Path target, CopyOption... options) 

    with CopyOptions ATOMIC_MOVE . 与CopyOptions ATOMIC_MOVE According to the javadocs , this may not be supported, but if it isn't supported you should get an exception. 根据javadocs ,这可能不受支持,但是如果不支持,则应获得一个异常。

But note that the atomicity is implemented in the OS, and if the OS cannot give strong enough guarantees, you are out of luck. 但是请注意,原子性是在OS中实现的,如果OS无法提供足够有力的保证,那么您很不走运。

(One issue is what might happen in the event of a hard disk error. If the disk dies completely, then atomicity is moot. But if the OS is still able to read the disk after the failure, then the outcome depends on the OS'es ability to repair the file system.) (一个问题是发生硬盘错误时会发生什么。如果磁盘完全死掉,那么原子性就没有意义了。但是,如果操作系统在故障后仍然能够读取磁盘,那么结果取决于操作系统具有修复文件系统的能力。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM