我正在尝试使用 JSCH 通过 SFTP 协议发送文件。
这是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");
}
}
Run Code Online (Sandbox Code Playgroud)
但正在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();
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出了以下消息java.io.IOException: channel is broken
Ogo*_*god 11
channel.connect()您只是错过了执行之前对 right 的调用channel.put(...)。这将设置 ,channel以便将内部变量io_in分配给 an 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");
}
}
Run Code Online (Sandbox Code Playgroud)