如何将 FileInputStream 转换为 InputStream?

我只是想把一个 FileInputStream转换成一个 InputStream,我该怎么做呢?

e.g

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

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.

为了回答你的一些评论..。

要将内容 InputStream 发送给远程使用者,需要将 InputStream 的内容写入 OutputStream,然后关闭两个流。

远程使用者对您创建的流对象一无所知。他只是在一个 InputStream 中接收内容,然后创建、读取和关闭这个 InputStream。

一个输入流。

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

当然是 这不是你想要的效果; 您返回的流已经关闭。只要返回 FileInputStream 就可以了。调用代码应该会关闭它。

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

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;


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;