Jonah Sloan Jonah Sloan - 17 days ago 6
Java Question

Getting the file used by a FileInputStream

Is it possible to obtain the

File
being used by a
FileInputStream
?
FileInputStream
does not appear to have any methods for retrieving it.

Answer

There are no direct methods in FileInputStream API, but if you really wanted, you can use java reflection API to get the path (actual file name with full path) as shown below:

FileInputStream fis = new FileInputStream(inputFile);
Field field = fis.getClass().getDeclaredField("path");
field.setAccessible(true);
String path  = (String)field.get(fis);
System.out.println(path);

The path variable (holds the file name with path) is declared in the FileInputStream class as a private final field, which we are getting it using reflections code as shown above.