File path/name from InputStream
How to obtain File Path/Name from an InputStream 开发者_如何学运维in Java ?
It's not possible. (not from the FileInputStream in the Java API). The FileInputStream
constructor does not store this information in any field:
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
open(name);
}
You can't because the InputStream
might not have been a file or path. You can implement your own InputStream
that generates data on the fly
Two important Object Oriented Design principles prevent you from doing what you're asking: abstraction and encapsulation.
- Abstraction is the process of defining a general concept that has only the details necessary for its use in a particular context (more details here). In this situation, the abstraction is
InputStream
, which is a general interface that can provide bytes, regardless of the source of those bytes. The abstraction of anInputStream
has no concept of a file path; that's only relevant to particular implementations ofInputStream
. - Encapsulation is the process of hiding implementation details of a class from consumers/users of that class. In this particular situation,
FileInputStream
encapsulates the details of the file it is reading from, because as anInputStream
that information is not relevant to the usage. Thepath
instance field is encapsulated and as such unavailable to users of the class.
Having said that, it is possible to access the path
variable if you are willing to accept some important limitations. Basically, the gist is that you can check if the InputStream
is, in fact, an instance of FileInputStream
and, if so, use reflection to read the path
instance field. I'll leave out the details of doing that access since it's easily discoverablein the java.lang.Class
Java docs and online, and not really a generally good thing to do in most contexts. Since the question doesn't provide a context about why, it's hard to offer any more reasonable approaches.
精彩评论