Sftp upload method in Java never quits

0
So I did a Java program 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 the force, I tried several But nd things 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();
    }

}
    
asked by anonymous 21.02.2017 / 21:47

1 answer

0

According to the example on the library site, you need to log out of the session using the method disconnect of 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();
        }
    }

}
    
21.02.2017 / 22:24