java - JavaFX 如何停止当前传输文件 SFTP
问题描述
我想使用以下方法停止我当前的传输文件stopUpload()
:
private ChannelSftp channelSftp
private ChannelSftp setupJsch() throws JSchException {
JSch jsch = new JSch();
jsch.setKnownHosts("/Users/john/.ssh/known_hosts");
Session jschSession = jsch.getSession(username, remoteHost);
jschSession.setPassword(password);
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
public void stopUpload()
{
channelSftp.disconnect();
}
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String localFile = "src/main/resources/sample.txt";
String remoteDir = "remote_sftp_test/";
channelSftp.put(localFile, remoteDir + "jschFile.txt");
channelSftp.exit();
}
当 stopUpload() 运行我有这个错误:Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
解决方案
要彻底取消 JSch SFTP 传输,请在需要时实现SftpProgressMonitor
接口:
public class CancellableProgressMonitor implements SftpProgressMonitor {
private boolean cancelled;
public CancellableProgressMonitor() {}
public void cancel() {
this.cancelled = true;
}
public bool wasCancelled() {
return this.cancelled;
}
public void init(int op, java.lang.String src, java.lang.String dest, long max) {
this.cancelled = false;
}
public boolean count(long bytes) {
return !this.cancelled;
}
public void end() {
}
}
并将其传递给ChannelSftp.put
:
CancellableProgressMonitor monitor = new CancellableProgressMonitor()
channelSftp.put(localFile, remoteDir + "jschFile.txt", monitor);
monitor.cancel()
当您需要取消转移时,请致电。
public void stopUpload() {
monitor.cancel();
}
如果要清理部分传输的文件:
String remoteFile = remoteDir + "jschFile.txt";
try {
channelSftp.put(localFile, remoteFile, monitor);
} catch (IOException e) {
if (monitor.wasCancelled() && channelSftp.getSession().isConnected()) {
try {
channelSftp.rm(remoteFile);
} catch (SftpException e) {
if (e.id == SSH_FX_NO_SUCH_FILE) {
// can happen if the transfer was cancelled
// before the file was even created
} else {
throw e;
}
}
}
throw e;
}
推荐阅读
- c# - 在将类保存到 xml 文件之前加密属性
- django - 在Django中的整个表(所有字段,所有列,所有行)中查找一个字符串
- php - 使用 gd 调整字体大小和填充以创建动态条形图
- c++ - 是否可以将成员作为指针继承?
- python - 我正在抓取沃尔玛,但是每当我输入带有要抓取的搜索 URL 的函数的参数时,当我尝试打印它时,我什么也得不到
- sql - 学生寻求 CSC 考试的建议
- postgresql - 从删除子查询返回值中选择
- c++ - 在家庭系统上安装 gtest 时出错
- java - 尝试在另一个模块中使用一个模块类时应用程序失败?
- bash - 如何使用 sed 在特定单词后添加单引号?