简体   繁体   English

使用 RandomAccessFile 读取文件属性

[英]Read file attributes using RandomAccessFile

Is it possible to get any of the file attributes using RandomAccessFile ?是否可以使用RandomAccessFile获取任何文件属性?

By file attributes I mean Unix implementation provided in the class UnixFileAttributes :文件属性是指 class UnixFileAttributes 中提供的UnixFileAttributes

class UnixFileAttributes
    implements PosixFileAttributes
{
    private int     st_mode;
    private long    st_ino;
    private long    st_dev;
    private long    st_rdev;
    private int     st_nlink;
    private int     st_uid;
    private int     st_gid;
    private long    st_size;
    private long    st_atime_sec;
    private long    st_atime_nsec;
    private long    st_mtime_sec;
    private long    st_mtime_nsec;
    private long    st_ctime_sec;
    private long    st_ctime_nsec;
    private long    st_birthtime_sec;

    //
}

Usage of third-party libraries is acceptable (and desirable) in case it is not possible to do that in plain Java.如果在普通 Java 中无法做到这一点,则可以接受(并且可取)使用第三方库。

In JDK, the only built-in bridge from Java land to fstat function is sun.nio.fs.UnixFileAttributes.get() method.在 JDK 中,从 Java 到fstat function 的唯一内置桥是sun.nio.fs.UnixFileAttributes.get()方法。 This is private API, which can be called only using Reflection.这是私有的API,只能使用Reflection调用。 But it works in all versions of OpenJDK from 7 to 14.但它适用于从 7 到 14 的所有版本的 OpenJDK。

    public static PosixFileAttributes getAttributes(FileDescriptor fd)
            throws ReflectiveOperationException {

        Field f = FileDescriptor.class.getDeclaredField("fd");
        f.setAccessible(true);

        Class<?> cls = Class.forName("sun.nio.fs.UnixFileAttributes");
        Method m = cls.getDeclaredMethod("get", int.class);
        m.setAccessible(true);

        return (PosixFileAttributes) m.invoke(null, f.get(fd));
    }

    public static void main(String[] args) throws Exception {
        try (RandomAccessFile raf = new RandomAccessFile(args[0], "r")) {
            PosixFileAttributes attr = getAttributes(raf.getFD());
            System.out.println(attr.permissions());
        }
    }

Other possible solutions would involve native libraries (JNI / JNA / JNR-FFI).其他可能的解决方案将涉及本机库(JNI / JNA / JNR-FFI)。 But you'd still need to obtain a native fd from FileDescriptor object, either using Reflection or JNI.但是您仍然需要使用反射或 JNI 从FileDescriptor object 获取本机 fd。

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

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