我正在使用 JSch 将文件上传到 SFTP。它可以工作,但有时 TCP 连接会在上传文件时关闭,导致服务器上的文件被截断。
我发现reput SFTP 服务器上的命令恢复上传。如何使用 JSch 发送 reput 命令?这可能吗?
这是我的代码:
public void upload(File file) throws Exception
{
JSch jsch = new JSch();
Session session = jsch.getSession(USER, HOST, PORT);
session.setPassword(PASSWORD);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel=session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp)channel;
sftpChannel.put(file.getAbsolutePath(), file.getName());
channel.disconnect();
session.disconnect();
}
最佳答案
我找到了办法。使用带有 RESUME 参数的“put”方法:
sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.RESUME);
我的代码变成:
public static void upload(File file, boolean retry) {
try
{
System.out.println("Uplodaing file " + file.getName());
JSch jsch = new JSch();
Session session = jsch.getSession(USER, HOST, PORT);
session.setPassword(PASSWORD);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
if (!retry)
sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.OVERWRITE);
else
sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.RESUME);
channel.disconnect();
session.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
upload(file, true);
}
}
关于java - 如何在 JSch SFTP 上获得声誉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891498/