有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在JSch SFTP上重新发布?

我正在使用JSch将文件上载到SFTP。它可以工作,但有时在上载文件时TCP连接会关闭,从而导致服务器上的文件被截断

我发现SFTP服务器上的reput命令会恢复上传。如何使用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();
}

共 (1) 个答案

  1. # 1 楼答案

    我找到了一条路。对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);
        }
    
    }