如何在Java11中获取POSIX文件描述符?
我有一个方法,它使用如何在Java11中获取POSIX文件描述符?,java,java-11,Java,Java 11,我有一个方法,它使用sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().get(FileDescriptor)byJava8来获取真正的POSIX文件描述符。在Java9(及更高版本)SharedSecrets被迁移到jdk.internal.misc 如何在Java11中获取POSIX文件描述符 private int getFileDescriptor() throws IOException { final int fd
sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().get(FileDescriptor)
byJava8来获取真正的POSIX文件描述符。在Java9(及更高版本)SharedSecrets被迁移到jdk.internal.misc
如何在Java11中获取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;
}
private int getFileDescriptor()引发IOException{
final int fd=SharedSecrets.getJavaIOFileDescriptorAccess().get(getFD());
如果(fd<1)
抛出新IOException(“获取POSIX文件描述符失败!”);
返回fd;
}
提前谢谢 这仅在紧急情况下使用(或者直到您找到一种不同的方法,因为它不受支持),因为它会执行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();
}
}
}
没有支持的方法来执行此操作。你在问题中遇到的黑客太脆弱了,随时可能崩溃。你解决过你的问题吗?我正试图让PI4J开发我的Raspberry Pi,它只有Java11,并且面临同样的问题。我决定最好用python来编写raspberry pi。谢谢,这对我有帮助。我将找到不同的方法我发现行“field.setAccessible(true);”抛出一个不可访问的对象异常,异常消息为“无法使字段私有int java.io.FileDescriptor.fd可访问:module java.base未”打开java.io“到module FileTest”。我假设有一种方法可以访问这个字段,因为它在Eclipse调试器中是可见的。@StevenF.LeBrun取决于JDK版本,我想知道这个漏洞是否已经在较新版本的JDK中堵塞了,因为这肯定是一个黑客行为。