SFTP/FTP JAVA file upload or download from FTP Server
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 39 40 41 | private String host="host"; private String user="user"; private String pwd="password"; private String localFileFullPath="C:/temp/file.txt"; private String remoteFileName="ftpFileName"; private String sftpWorkingDir="/ftpFolder/test; public void uploadFile() throws Exception{ JSch jsch = new JSch(); Session session = jsch.getSession(user, host,22); session.setPassword(pwd); 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 channelSftp = (ChannelSftp)channel; channelSftp.cd(sftpWorkingDir); channelSftp.put(new FileInputStream(new File(localFileFullPath)), remoteFileName); channelSftp.exit(); session.disconnect(); } public void downloadFile() throws Exception{ JSch jsch = new JSch(); Session session = jsch.getSession(user, host,22); session.setPassword(pwd); 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 channelSftp = (ChannelSftp)channel; channelSftp.cd(sftpWorkingDir); //channelSftp.put(new FileInputStream(new File(localFileFullPath)), remoteFileName); channelSftp.get(remoteFileName, new FileOutputStream(new File(localFileFullPath))); channelSftp.exit(); session.disconnect(); } |
No comments:
Post a Comment