Question

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();
}
Was it helpful?

Solution

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top