Frage

I have one file with another hardlink. How to change the first file in Java, while keep the content in another hardlink unchanged?

This behavior is like gVim in Windows:

C:\Users\atry\break-hard-link>echo Hello, World > file1

C:\Users\atry\break-hard-link>mklink /H file2 file1
为 file2 <<===>> file1 创建了硬链接

C:\Users\atry\break-hard-link>gvim file1 :: Change file1 in gVim

C:\Users\atry\break-hard-link>dir
 驱动器 C 中的卷没有标签。
 卷的序列号是 B2F2-1B6E

 C:\Users\atry\break-hard-link 的目录

2012-11-04  11:33    <DIR>          .
2012-11-04  11:33    <DIR>          ..
2012-11-04  11:33                 8 file1
2012-11-04  11:32                15 file2
               2 个文件             23 字节
               2 个目录 365,748,248,576 可用字节

Note that file1's size and file2's size are different now.

I have tried new java.io.FileOutputStream and java.nio.file.Files.newOutputStream, but both methods modified both file1 and file2.

I want know how gVim does, and apply same behavior in my Java application.

War es hilfreich?

Lösung

I don't know how gVim does it but the reliable way to do this is to

  1. rename the old file (this will rename only the link you select)
  2. copy the data to a new file with the old name
  3. when you're sure the new file was created and closed successfully, remove the old file

The only way to get a new inode (which is what is required to break the link) is to make a new copy of the data.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top