Java Sftp upload method never ends

Asked

Viewed 221 times

0

So, I made a program in Java using Netbeans to upload an "X" file to an SFTP server and the method is functional, but once I start the program, it just shuts down, I’ve tried several things but nd solved my problem. My code is:

public void Upload(String localfile) {
    String SFTPHOST = "example.com";
    int SFTPPORT = 22;
    String SFTPUSER = "user";
    String SFTPPASS = "pass";
    String SFTPWORKINGDIR = "/var/";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(localfile);
        channelSftp.put(new FileInputStream(f), f.getName());
        channelSftp.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
  • What library are you using? Where are the classes JSch, Session, Channel and ChannelSftp?

  • 1

    Ah, I’ve got it: http://www.jcraft.com/jsch/

1 answer

0


According to the example on the library website, you need to disconnect from the session using the method disconnect class Session.

public void Upload(String localfile) {
    String SFTPHOST = "example.com";
    int SFTPPORT = 22;
    String SFTPUSER = "user";
    String SFTPPASS = "pass";
    String SFTPWORKINGDIR = "/var/";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(localfile);
        channelSftp.put(new FileInputStream(f), f.getName());
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if(channelSftp != null) {
            channelSftp.disconnect();
        }
        if(session != null) {
            session.disconnect();
        }
    }

}
  • Po man thanks, I even saw that I should use Disconnect but all the ways I wrote it, I wrote it wrong, it worked right! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.