gpt4 book ai didi

JavaFX 如何停止当前传输文件 SFTP

转载 作者:行者123 更新时间:2023-12-04 08:52:50 24 4
gpt4 key购买 nike

我想使用方法 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 interface :

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;
}

关于JavaFX 如何停止当前传输文件 SFTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64009763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com