首页 > 代码库 > JAVA代码时间SFTP文件的下载
JAVA代码时间SFTP文件的下载
参考文章:http://blog.csdn.net/smallerpig/article/details/50976191
SFTP文件的下载与FTP文件的下载差别较大,需要下载jsch-0.1.54jar包
package com.cd.util; import com.jcraft.jsch.JSchException; public class SftpDownloadTestScript { public static void main (String[] args)throws JSchException { String ftpHost = "192.168.188.155"; String ftpUserName = "exftp"; String ftpPassword = "sFtP06222013"; int ftpPort = 22; String ftpPath = "."; String localPath = "D:/SFTP/uploadFiles/demo"; String fileName = "aa.jpg"; FtpUtil.downloadSftpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName); } }
package com.cd.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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; public class FtpUtil { private final static Log logger = LogFactory.getLog(FtpUtil.class); /* * 从SFTP服务器下载文件 * * @param ftpHost SFTP IP地址 * * @param ftpUserName SFTP 用户名 * * @param ftpPassword SFTP用户名密码 * * @param ftpPort SFTP端口 * * @param ftpPath SFTP服务器中文件所在路径 格式: ftptest/aa * * @param localPath 下载到本地的位置 格式:H:/download * * @param fileName 文件名称 */ public static void downloadSftpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName) throws JSchException { Session session = null; Channel channel = null; JSch jsch = new JSch(); System.out.println(1); session = jsch.getSession(ftpUserName, ftpHost, ftpPort); System.out.println(2); session.setPassword(ftpPassword); System.out.println(3); session.setTimeout(100000); System.out.println(4); Properties config = new Properties(); System.out.println(5); config.put("StrictHostKeyChecking", "no"); System.out.println(6); session.setConfig(config); System.out.println(7); session.connect(); System.out.println(8); channel = session.openChannel("sftp"); System.out.println(9); channel.connect(); ChannelSftp chSftp = (ChannelSftp) channel; System.out.println(10); String ftpFilePath = ftpPath + "/" + fileName; String localFilePath = localPath + File.separatorChar + fileName; System.out.println(11); try { System.out.println("ftpFilePath="+ftpFilePath); System.out.println("localFilePath="+localFilePath); System.out.println("localPath="+localPath); chSftp.get(ftpFilePath, localPath); System.out.println(13); } catch (Exception e) { e.printStackTrace(); logger.info("download error."); } finally { chSftp.quit(); channel.disconnect(); session.disconnect(); } } }
下面是SFTP根目录:
JAVA代码时间SFTP文件的下载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。