Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File path/name from InputStream

How to obtain File Path/Name from an InputStream in Java ?

like image 368
Muhammad Hewedy Avatar asked Mar 23 '10 17:03

Muhammad Hewedy


People also ask

Can we get file name from InputStream?

is it possible ? I'm afraid I can't follow precisely what you're asking, but: there's no way to get the filename that a FileOutputStream or FileInputStream is connected to, even within a single JVM; it's doubly impossible in a client/server situation.

How do I find a file from FileInputStream?

int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format). This method returns -1 if the end of the file is reached. int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array.

What is FileInputStream in Java?

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .

What does InputStream read return?

Returns. the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.


2 Answers

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);
    }
like image 121
b.roth Avatar answered Oct 27 '22 18:10

b.roth


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

like image 43
Pyrolistical Avatar answered Oct 27 '22 19:10

Pyrolistical