【问题标题】:creating a java wrapper for an inputstream function为输入流函数创建一个 java 包装器
【发布时间】:2018-07-09 00:53:09
【问题描述】:

我正在尝试读取文件输入流,然后将其传递给调用函数,然后在网络服务器应用程序查看器中播放该函数。下载工作正常,但问题是如果我在同一个函数中关闭流(推荐),调用函数由于某种原因收到一个空流。有人建议创建一个输入流包装器,这将允许我关闭流、删除文件并仍然将流传递给调用函数。

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 {

成为包装器,但我不知道该怎么做。 关于如何有效地做到这一点的任何建议或想法/链接。同样的问题是关闭流但能够将其传递给调用函数。

【问题讨论】:

    标签: java inputstream wrapper fileinputstream


    【解决方案1】:

    您应该将 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
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用组合来实现此 InputStream。 只需覆盖所有方法,以便它们调用您的委托对象。

      但我不确定这是做你想做的事情的正确方法。我认为这里最好的选择是向函数添加输出流。然后该函数会将它读取的内容写入输出流,调用者现在负责关闭流。 (Easy way to write contents of a Java InputStream to an OutputStream)

      【讨论】:

      • 感谢您的回复;将查看链接并尝试实施
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      相关资源
      最近更新 更多