[java] How to convert FileInputStream to InputStream?

I just want to convert a FileInputStream to an InputStream, how can I do that?

e.g

FileInputStream fis = new FileInputStream("c://filename");
InputStream is = ?; 
fis.close();

This question is related to java fileinputstream

The answer is


You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.

If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.

To answer some of your comments...

To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.

The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.


If you wrap one stream into another, you don't close intermediate streams, and very important: You don't close them before finishing using the outer streams. Because you would close the outer stream too.


InputStream is = new FileInputStream("c://filename");
return is;

InputStream is;

try {
    is = new FileInputStream("c://filename");

    is.close(); 
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

return is;

FileInputStream is an inputStream.

FileInputStream fis = new FileInputStream("c://filename");
InputStream is = fis;
fis.close();  
return is;

Of course, this will not do what you want it to do; the stream you return has already been closed. Just return the FileInputStream and be done with it. The calling code should close it.