File id for keeping track of file changes in Java?

后端 未结 2 1662
自闭症患者
自闭症患者 2020-12-22 09:20

I\'m trying to find a way to keep track of files even when they are moved or renamed in the file system.

One idea I had was to use the new UserDefinedFileAttributeVi

相关标签:
2条回答
  • 2020-12-22 09:26

    I tried the Oracle example on a Windows XP computer. There was a very minor bug in the code example, but other than this, the code worked fine -- at least on Windows XP. Hopefully it would also work on Linux etc, but I personally have only tried it on 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);
    

    Just to be sure the attribute was not just being read from the view, I also ran the same code using a 2nd view. This also worked...

    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);
    
    
    }
    

    It would be great if such custom file attributes work across all the major platforms, as such custom file attributes are incredibly handy in some situations. Hope they do.

    0 讨论(0)
  • 2020-12-22 09:33

    This is not implemented on the OSX version of Java. This bug is still open: https://bugs.openjdk.java.net/browse/JDK-8030048

    This bug was closed, https://bugs.openjdk.java.net/browse/JDK-8040830, with a reference to use a 3rd party workaround (which I haven't tried): https://github.com/IsNull/xattrj

    0 讨论(0)
提交回复
热议问题