我正在尝试读取文件输入流,然后将其传递给调用函数,然后在网络服务器应用程序查看器中播放该函数。下载工作正常,但问题是,如果我在同一函数中关闭流(推荐),则调用函数会因某种原因收到空流。有人建议创建一个输入流包装器,这将允许我关闭流、删除文件并仍然将流传递给调用函数。
public InputStream exportVideo(Youtube connection, String videoID) {
InputStream is = null;
....//file retrieval code above
is = new FileInputStream(ndirectory + "\\" + this.videoID.toString()
+ ".avi");
return is;
....//trace handling code below
finally{
is.close();
}
}
调用函数:
stream = FetchVideo.exportVideo(econnection, videoID);
我认为这个建议的意思是上一些课:
public class StreamConverter extends InputStream {
作为包装器,但我不知道该怎么做。 关于如何有效地做到这一点的任何建议或想法/链接。同样,问题是关闭流但能够将其传递给调用函数。
最佳答案
您应该将 is.close()
调用移出方法并在获得它的位置关闭它,例如
try {
stream = FetchVideo.exportVideo(econnection, videoID);
//do something with the stream
}
finally {
if (stream != null) {
stream .close();
}
}
或者最好使用try with resource
try (InputStream stream = FetchVideo.exportVideo(econnection, videoID)) {
//do something with the stream
}
关于java - 为输入流函数创建 java 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48516310/