将 Jsch 与 InputStream 一起使用会抛出 NullPointerException

Use Jsch with InputStream is throwing NullPointerException

我正在尝试通过 SFTP 协议使用 JSCH 发送文件。

这是FileService文件

public class FileService {

    public void send(){
        String str = "this is a test";
        InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
        try {
            var channel = setupJsch();
            channel.put(is, "test.txt");
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }
    
    private ChannelSftp setupJsch() throws JSchException {
        JSch jsch = new JSch();
        Session jschSession = jsch.getSession("foo", "localhost", 2222);
        jschSession.setPassword("pass");
        jschSession.setConfig("StrictHostKeyChecking", "no");
        jschSession.connect();
        return (ChannelSftp) jschSession.openChannel("sftp");
    }
}

但是 JSch 抛出 NullPointException 消息: java.lang.NullPointerException: Cannot invoke "com.jcraft.jsch.Channel$MyPipedInputStream.updateReadSide()" because "this.io_in" is null

我已经用 OutputStream 试过了,结果是一样的。

你能帮帮我吗?

[更新 1]

尝试@Ogod 的建议后

    public void send(){
        String str = "this is a test";
        InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
        try {
            var channel = setupJsch();
            channel.start();
            channel.put(is, "test.txt");
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }

已抛出以下消息java.io.IOException: channel is broken

您只是在执行 channel.put(...) 之前错过了对 channel.connect() 的调用。这将设置 channel,以便将内部变量 io_in 分配给 InputStream(这修复了 NullPointerException)。

此外,如果您不再需要 channel,您应该通过调用 channel.disconnect()channel.exit() 正确关闭它。这将确保释放所有资源。

public class FileService {

    public void send(){
        String str = "this is a test";
        InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
        try {
            var channel = setupJsch();
            channel.connect();   // this should do the trick
            channel.put(is, "test.txt");
            channel.exit();      // don't forget this
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }
    
    private ChannelSftp setupJsch() throws JSchException {
        JSch jsch = new JSch();
        Session jschSession = jsch.getSession("foo", "localhost", 2222);
        jschSession.setPassword("pass");
        jschSession.setConfig("StrictHostKeyChecking", "no");
        jschSession.connect();
        return (ChannelSftp) jschSession.openChannel("sftp");
    }
}