Java 如何获取 inputStream 正在使用的文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21402779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the file name of the one being used by a inputStream?
提问by user657592
I have a method accepts an InputStream as an argument. How do I find which file is being handled by the passed handler?
我有一个方法接受 InputStream 作为参数。如何找到传递的处理程序正在处理哪个文件?
For example:
例如:
public performSomething(InputStream inputStream) {
System.out.println(FILENAME);
}
What should the FILENAME be replaced with such that the name of the file opened by the handler is displayed.
应该用什么来替换 FILENAME,以便显示处理程序打开的文件的名称。
采纳答案by Svetlin Zarev
I guess you cannot, because the input stream might not belong to a file. It can be SocketInputStream
, or ByteArrayInputStream
for example. The input stream is just an abstraction
我猜你不能,因为输入流可能不属于一个文件。它可以是SocketInputStream
,或者ByteArrayInputStream
例如。输入流只是一个抽象
回答by Java Curious ?
An input stream can be created to read from a file or from any other source of data. Therefore it makes no sense to have a filename attached to an input stream.
可以创建输入流以从文件或任何其他数据源读取。因此,将文件名附加到输入流是没有意义的。
Simple Example :
简单示例:
InputStream input= assetInfo.openStream();
File t = new File("");
OutputStream out = new FileOutputStream(t);
int read=0;
byte[] bytes = new byte[1024];
while((read = input.read(bytes))!= -1){
out.write(bytes, 0, read);
}
Look in assetInfo to see if that class exposes that data (you can even look inside the class using reflection). Note that the creator or assetInfo made a design mistake not exposing this information, OR you are trying to make one now.
查看 assetInfo 以查看该类是否公开了该数据(您甚至可以使用反射查看该类的内部)。请注意,创建者或资产信息犯了一个设计错误,没有公开此信息,或者您现在正在尝试制作一个。
回答by Marko Topolnik
Even if you are certain you have a FileInputStream
, you will still be unable to get the underlying file. FileInputStream
does not retain its File
argument, but immediately opens the file and retains just the FileDescriptor
, a wrapper around the native int
handle to the OS resource.
即使你确定你有一个FileInputStream
,你仍然无法获得底层文件。FileInputStream
不保留其File
参数,但会立即打开文件并仅保留FileDescriptor
, 围绕int
操作系统资源的本机句柄的包装器。
As of OpenJDK version 7, Update 40, a String path
variable has been introduced, so with some luck you may try to reflectivelyget it.
从 OpenJDK 版本 7 Update 40 开始,String path
已经引入了一个变量,所以如果运气好的话,您可以尝试反射性地获取它。
Of course, this can be nothing more than heurstics. There is no official way through the public API.
当然,这无非是启发式。没有通过公共 API 的官方方法。