Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert FileInputStream to InputStream? [closed]

People also ask

Does FileInputStream need to be closed?

Yes, you need to close the inputstream if you want your system resources released back. FileInputStream. close() is what you need.

How do you close InputStream?

Closing an InputStream You close an InputStream by calling the InputStream close() method. Here is an example of opening an InputStream , reading all data from it, and then closing it: InputStream inputstream = new FileInputStream("c:\\data\\input-text. txt"); int data = inputstream.

Can we convert OutputStream to InputStream in Java?

Though you cannot convert an OutputStream to an InputStream, java provides a way using PipedOutputStream and PipedInputStream that you can have data written to a PipedOutputStream to become available through an associated PipedInputStream.


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;

InputStream is = new FileInputStream("c://filename");
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.


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.