Search code examples
javasftpinputstreamjsch

JSch "pipe closed" when using SFTP download InputStream after disconnect


I am using JSch to open a SFTP channel to a remote server. I use the below code to open the connection and download the file:

public org.springframework.core.io.Resource download(){
    JSch jsch = new Jsch();
    Session session = jsch.get("root", "192.168.1.10", 22);
    session.setPassword("root");
    session.setConfig("StrictHostKeyChecking","no");
    session.connect();
    ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
    channelSftp.connect();
    InputStream is = channelSftp.get("/root/example.mp4");
    channelSftp.exit();
    session.disconnect();
    return new org.springframework.core.io.InputStreamResource(is);    
}

The problem is:

  1. If I use exit() and/or disconnect() method, there will be Pipe closed exception thrown
  2. If I don't, my method return a Resource successfully but the channel/session is still in connected state.

So I have a question for this implementation whether there is something wrong ? If there isn't, will the number of sessions increase till the SFTP server denies or they will be closed at a time in future, how can I handle this ?

Thank you in advanced


Solution

  • You cannot access the data after you disconnect.

    If the API needs InputStream and you then lose the control, you can implement a wrapper InputStream implementation that delegates all calls to your is, and calls disconnect once InputStream.close is called.


    Easier but less efficient solution for not-too-large files is to read the JSch stream to memory (to a byte array) and return the array or wrapper ByteArrayInputStream to your API.