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.@R_404_6422@connect();

}

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