问题描述
是否可以获取FileInputStream
正在使用的File
? FileInputStream
似乎没有任何检索它的方法.
Is it possible to obtain the File
being used by a FileInputStream
? FileInputStream
does not appear to have any methods for retrieving it.
推荐答案
FileInputStream
API中没有直接方法,但是如果您确实需要,可以使用Java Reflection API获取path
(实际文件名).完整路径),如下所示:
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);
path
变量(带有路径的文件名)在FileInputStream
类中声明为私有的final字段,我们使用上面显示的反射代码来获取它.
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.
PS: 您需要注意,由于规范中未定义上述方法,因此不能保证上述方法在所有JVM实现中都能达到结果.
这篇关于获取FileInputStream使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!