如何在Java 11中获取POSIX文件描述符?

问题描述 投票:2回答:1

我有方法,它使用Java 8的sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().get(FileDescriptor)来获取真正的POSIX文件描述符。在Java 9(及更高版本)中,SharedSecrets已迁移到jdk.internal.misc

如何在Java 11中获取POSIX文件描述符?

private int getFileDescriptor() throws IOException {
      final int fd = SharedSecrets.getJavaIOFileDescriptorAccess().get(getFD());
      if(fd < 1)
                throw new IOException("failed to get POSIX file descriptor!");

      return fd;
}

提前致谢!

java java-11
1个回答
1
投票

这仅用于紧急情况(或直到您找到不同的方式,因为它不受支持),因为它做了API无意识的事情并且不受支持。买者自负。

package sandbox;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;

public class GetFileHandle {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("somedata.txt")) {
            FileDescriptor fd = fis.getFD();

            Field field = fd.getClass().getDeclaredField("fd");
            field.setAccessible(true);
            Object fdId = field.get(fd);
            field.setAccessible(false);

            field = fd.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            Object handle = field.get(fd);
            field.setAccessible(false);

            // One of these will be -1 (depends on OS)
            // Windows uses handle, non-windows uses fd
            System.out.println("fid.handle="+handle+"  fid.fd"+fdId);
        } catch (IOException | NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.