0

I am trying to read a fileinputstream that then gets passed to a calling function which is then played back in a webserver application viewer. The download works fine but the problem is that if I close the stream (which is recommended) within the same function the calling function receives a null stream for some reason. Someone suggested creating an inputstream wrapper and this will allow me to close the stream, delete the file and still pass the stream to the calling function.

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

  }

the calling function:

 stream = FetchVideo.exportVideo(econnection, videoID);

what I am thinking the suggestion meant was have some class:

public class StreamConverter extends InputStream {

be the wrapper, but I have no idea how to do this. Any advice or ideas / links on how to do this effectively. Again the problem is closing the stream but being able to pass it on to the calling function.

vbNewbie
  • 3,291
  • 15
  • 71
  • 155

2 Answers2

1

You should move the is.close() call out of the method and close it where you get it e.g

try {
    stream = FetchVideo.exportVideo(econnection, videoID);
    //do something with the stream
}
finally {
    if (stream != null) {
        stream .close();
    }
}

or it's better to use try with resource

try (InputStream stream = FetchVideo.exportVideo(econnection, videoID)) {
    //do something with the stream
}
StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

You could use composition to implement this InputStream. Just override all methods so they call your delegate object.

But I am not sure this is the right way to do what you want. I think the best option here is to add an output stream to the function. The function will then write the content it reads to the output stream and the caller is now in charge of closing the stream. (Easy way to write contents of a Java InputStream to an OutputStream)

Frol
  • 126
  • 1
  • 5