我有一个方法,它使用sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().get(FileDescriptor)通过Java 8获得真正的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;
}提前感谢!
发布于 2019-04-04 12:44:34
这只能在紧急情况下使用(或者直到您找到另一种方法,因为这是不支持的),因为它会做一些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();
}
}
}https://stackoverflow.com/questions/55512615
复制相似问题