I have method, which using sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().get(FileDescriptor)
by Java 8 for getting the real POSIX file descriptor. In Java 9 (and upper) SharedSecrets was migrated to jdk.internal.misc
.
How can I get POSIX file descriptor in Java 11?
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;
}
Thanks in advance!
This is only to be used in case of emergency (or until you find a different way since this is not supported) because it does things unintended by the API and is not supported. Caveat emptor.
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();
}
}
}