Is it possible to obtain the File
being used by a FileInputStream
? FileInputStream
does not appear to have any methods for retrieving it.
Asked
Active
Viewed 7,203 times
3

Jenna Sloan
- 372
- 8
- 22
-
you can use reflections as shown in my answer, have a look – Vasu Nov 20 '16 at 06:32
1 Answers
5
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.
P.S.: You need to NOTE that the above approach can't be guaranteed to achieve the result across all of the JVM implementations as it is not defined in the specification.

Vasu
- 21,832
- 11
- 51
- 67
-
This only works for implementations of `FileInputStream` that have such a member. There's nothing in the contract that requires it. – user207421 Nov 20 '16 at 08:36
-
In fact I cannot find such a field in JDK 1.6, 1.7, or 1.8, for either `FileInputStream` or `FileOutputStream`. Have you tested this? – user207421 Nov 20 '16 at 09:05
-
-
Also, just looked at the class file which shows this variable: private final String path; – Vasu Nov 20 '16 at 09:12
-
Which version? Not present in the ones I mentioned. 1.7 and 1.8 are OpenJDK, the other is src.zip as distributed with the JDK. It seems to me that you're looking at `java.io.File`. There is no reason why `FileInputStream` should store a `path` variable. It isn't needed beyond the constructor. – user207421 Nov 20 '16 at 09:15
-