簡體   English   中英

JavaFX 如何停止當前傳輸文件SFTP

[英]JavaFX How to stop current transfer file 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM