问题
Is it possible to obtain the File
being used by a FileInputStream
? FileInputStream
does not appear to have any methods for retrieving it.
回答1:
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.
来源:https://stackoverflow.com/questions/40700958/getting-the-file-used-by-a-fileinputstream