用于跟踪Java中文件更改的文件ID?

我试图find一种方法来跟踪文件,即使它们在文件系统中被移动或重命名。

我想到的一个想法是在Java 7中使用新的UserDefinedFileAttributeView,并创build一个自定义文件属性作为一种自定义ID。 我认为这可能适用于不同的平台(主要是Windows和Mac)。 但是我无法让它工作。 甚至尝试在这个页面上的例子 – http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html – 当我到这一行:

UserDefinedFileAttributeView view = Files.getFileAttributeView(file,UserDefinedFileAttributeView.class);

我只得到一个null值的视图variables,然后程序停止与一个空指针exception。

然后,我发现至less有一个可能更简单的方法来使用Mac:使用BasicFileAttributes fileKey属性。 我试过这个,即使我移动文件或重命名它,fileKey似乎也保持不变。 然而,它也说这个function是依赖于平台的,而且我记得在某个地方,它不能在Windows上工作。

所以首先,fileKey方法是在Mac上这样做的一个稳定的方法? 如果是这样,我可以做什么用于Windows相同的function? 任何人都知道为什么我在UserDefinedFileAttributeView上得到空值? 因为如果我能做到这一点,我猜应该是跨平台的。

这不是需要超级健壮和可伸缩的东西,它只是我正在开发的一个小型帮助器应用程序,但是在移动或重命名文件时至less需要可靠的识别文件。

我在Windows XP计算机上尝试了Oracle示例。 代码示例中有一个小错误,但除此之外,代码工作正常 – 至少在Windows XP上。 希望它也可以在Linux上工作,但我个人只在Windows XP上试过。

public static void main(String args[]) throws Exception { Path target = Paths.get("C:\\mytemp\\Something.txt"); Files.createFile(target); UserDefinedFileAttributeView view = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class); view.write("user.mimetype", Charset.defaultCharset().encode("text/html")); String name = "user.mimetype"; ByteBuffer buf = ByteBuffer.allocate(view.size(name)); view.read(name, buf); buf.flip(); String value = Charset.defaultCharset().decode(buf).toString(); System.out.println("value="+value); 

为了确保该属性不仅仅是从视图中读取,我还使用第二个视图运行相同的代码。 这也工作…

 public static void main(String args[]) throws Exception { Path target = Paths.get("C:\\mytemp\\SomethingDifferent.txt"); Files.createFile(target); UserDefinedFileAttributeView view = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class); view.write("user.mimetype", Charset.defaultCharset().encode("text/html")); String name = "user.mimetype"; UserDefinedFileAttributeView view2 = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class); ByteBuffer buf = ByteBuffer.allocate(view2.size(name)); view2.read(name, buf); buf.flip(); String value = Charset.defaultCharset().decode(buf).toString(); System.out.println("value="+value); } 

如果这样的自定义文件属性适用于所有主要平台,那将是非常好的,因为这样的自定义文件属性在某些情况下非常方便。 希望他们这样做。

这不是在OSX版本的Java上实现的。 这个bug仍然是开放的: https : //bugs.openjdk.java.net/browse/JDK-8030048

此错误已关闭, https://bugs.openjdk.java.net/browse/JDK-8040830 ,引用使用第三方解决方法(我没有尝试过): https : //github.com/IsNull / xattrj