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.
InputStream
, which is a general interface that can provide bytes, regardless of the source of those bytes. The abstraction of an InputStream
has no concept of a file path; that's only relevant to particular implementations of InputStream
.FileInputStream
encapsulates the details of the file it is reading from, because as an InputStream
that information is not relevant to the usage. The path
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.