How to convert FileInputStream to InputStream?

JavaFileinputstream

Java Problem Overview


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();

Java Solutions


Solution 1 - Java

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;

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionranjanView Question on Stackoverflow
Solution 1 - JavaKumar Vivek MitraView Answer on Stackoverflow
Solution 2 - JavaSumit SinghView Answer on Stackoverflow
Solution 3 - JavaJoeri HendrickxView Answer on Stackoverflow
Solution 4 - JavasudocodeView Answer on Stackoverflow
Solution 5 - Javauser unknownView Answer on Stackoverflow