【发布时间】:2021-06-04 10:31:13
【问题描述】:
我正在尝试通过 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
【问题讨论】:
-
@user207421 原来的错误是
NullPointerException。在评论中(现在已删除 - 为什么?)我建议在channel.put(...)之前尝试channel.start()。因为这个建议并不完全正确,下一个错误是IOException。 -
channel.start()只是朝着正确方向迈出的一步,但不应在外部调用此方法。正确的方法是channel.connect(),我的答案中写下了。无论如何,应该删除问题中的块 [Update 1],因为如果没有不再可用的 cmets,它会令人困惑。