How to reput on JSch SFTP?

╄→尐↘猪︶ㄣ 提交于 2019-12-10 11:27:29

问题


I'm using JSch to upload files to a SFTP. It works but sometimes the TCP connection is shut down while a file is being uploaded resulting on a truncated file on the server.

I found out that the reput command on SFTP servers resumes the upload. How can I send a reput command with JSch? Is it even possible?

Here's my code:

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:


I found a way. Use the "put" method with the RESUME parameter:

sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.RESUME);

My code became:

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

}


来源:https://stackoverflow.com/questions/21891498/how-to-reput-on-jsch-sftp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!