Getting the file used by a FileInputStream [duplicate]

半城伤御伤魂 提交于 2020-04-16 02:06:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!