Here is a code example that shows how to download and upload a file through SFTP in java
Download File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; /** * * @author javagists.com * */ public class DownloadFileSFTP { public static void main(String[] args) throws Exception { JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession("admin", "127.0.0.1", 22); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword("pass"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.get("/tmpremote/testDownload.txt", "/tmplocal/testDownload.txt"); sftpChannel.exit(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } } } |
Upload File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; /** * * @author javagists.com * */ public class UploadFileSFTP { public static void main(String[] args) throws Exception { JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession("admin", "127.0.0.1", 22); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword("pass"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.put("/tmplocal/testUpload.txt", "/tmpremote/testUpload.txt"); sftpChannel.exit(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } } } |
Short and simple, work for me
awesome, works like a charm. nicely done.
How do we get JSch class?
com.jcraft.jsch.JSchException: Session.connect: java.io.IOException: End of IO Stream Read
I got this exception while connecting to session..
any resolution for this?
Waste not workiing
what doesn’t work for you?