2
votes

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

2

2 Answers

3
votes

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.

1
votes

You must not read from the input stream after disconnect() is called. Either read data first from the stream and then call disconnect(), or use channelSftp.get(sourceDir, destinationDir) to download the file to a local destination directory in the local filesystem before you call disconnect().