java实现FTP和 SFTP连接远程服务器下载文件

时间:2025-01-15 14:40:49
/** * SFTP上传下载文件 */ public class SftpUtils { private final Logger logger = LoggerFactory.getLogger(SftpUtils.class);// (()); private static String ftpHost; // IP private static int ftpPort; // port private static String ftpUserName; // 用户 private static String ftpPassword; // 密码 /** * 连接sftp服务器 * @param host 主机 * @param port 端口 * @param username 用户名 * @param password 密码 * @return */ public ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; Channel channel=null; Session sshSession=null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); if(logger.isInfoEnabled()){ logger.info("***************** Session created. **********************"); logger.info("***************** stf host is "+host+"port is "+port+" username is "+username+" password is "+password+"**********************"); } sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); if(logger.isInfoEnabled()){ logger.info("***************** Session connected. **********************"); logger.info("***************** Opening Channel. **********************"); } channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; if(logger.isInfoEnabled()){ logger.info("***************** Connected to " + host + ". **********************"); } } catch (Throwable e) { if (channel!=null) { try { channel.disconnect(); }catch(Throwable e1) { } } if (sshSession!=null) { try { sshSession.disconnect(); }catch(Throwable e1) { } } logger.error(e.getMessage(), e); } return sftp; } /** * 关闭连接 * @param sftp */ public void disconnect(String host, ChannelSftp sftp){ // 关闭连接 try { if (null != sftp) { sftp.disconnect(); if(logger.isInfoEnabled()){ logger.info("***************** Closing Channel. **********************"); } if (null != sftp.getSession()) { sftp.getSession().disconnect(); if(logger.isInfoEnabled()){ logger.info("***************** Session disconnect. **********************"); } } } if (logger.isInfoEnabled()) { logger.info("**************** Disconnect to " + host + ". *******************"); } } catch (Exception e) { e.printStackTrace(); } } /** * 判断目录下是否存在文件或者文件夹 * @param directory * @param fileName * @param sftp * @return */ public boolean isExist(String directory, String fileName, ChannelSftp sftp) { try { Vector<LsEntry> v = listFiles(directory, sftp); Iterator<LsEntry> it = v.iterator(); while (it.hasNext()) { LsEntry entry = it.next(); String flName = entry.getFilename(); if (flName.equals(fileName)) { return true; } } } catch (SftpException e) { e.printStackTrace(); } return false; } /** * 上传文件 * @param directory 上传的目录 * @param uploadFile 要上传的文件 * @param sftp */ public String upload(String directory, String uploadFile, ChannelSftp sftp) { String successFlg = "0"; try { sftp.cd(directory); File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); if(logger.isInfoEnabled()){ logger.info("***************** Finished **********************"); } } catch (Exception e) { successFlg = "1"; e.printStackTrace(); } return successFlg; } /** * 下载文件 * @param directory 下载目录 * @param downloadFile 下载的文件 * @param saveFile 存在本地的路径 * @param sftp */ public String download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { String successFlg = "0"; try { sftp.cd(directory); File file = new File(saveFile); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } sftp.get(downloadFile, new FileOutputStream(file)); if(logger.isInfoEnabled()){ logger.info("***************** Finished **********************"); } } catch (Exception e) { successFlg = "1"; e.printStackTrace(); } return successFlg; } /** * 删除文件 * @param directory 要删除文件所在目录 * @param deleteFile 要删除的文件 * @param sftp */ public void delete(String directory, String deleteFile, ChannelSftp sftp) { try { sftp.cd(directory); sftp.rm(deleteFile); if(logger.isInfoEnabled()){ logger.info("***************** Finished **********************"); } if (null != sftp) { sftp.disconnect(); if (null != sftp.getSession()) { sftp.getSession().disconnect(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 列出目录下的文件 * @param directory 要列出的目录 * @param sftp * @return * @throws SftpException */ @SuppressWarnings("unchecked") public Vector<LsEntry> listFiles(String directory, ChannelSftp sftp) throws SftpException { return sftp.ls(directory); } /** * 初始化ftp信息,init()方法段逻辑你可以略过,自己去配置连接的参数信息 * 目前我们采用将Sftp连接参数,存在数据库里面了,所以写了一个查询配置信息的方法。 * @param type * @throws Exception */ public Map<String,String> init(String type) throws Exception { logger.info("***********************初始化SFTP信息***********************"); String hostMagicId = "CBS_HOST"; String userNameMagicId = "CBS_USERNAME"; String passWordMagicId = "CBS_PASSWORD"; String cbsPortMagicId="CBS_PORT"; Map<String, String> hashMap = new HashMap<>(); TblSysParam selectHost = DBDaos.newInstance().select(TblSysParam.class, "FTP", hostMagicId); if (selectHost == null) { SnowExceptionUtil.throwErrorException("请配置FTP地址!"); } ftpHost = selectHost.getParamValueTx(); hashMap.put(hostMagicId,ftpHost); TblSysParam selectPort = DBDaos.newInstance().select(TblSysParam.class, "FTP", cbsPortMagicId); if (selectPort == null) { SnowExceptionUtil.throwErrorException("请配置FTP端口!"); } ftpPort = Integer.parseInt(selectPort.getParamValueTx()); hashMap.put(cbsPortMagicId, String.valueOf(ftpPort)); TblSysParam selectUsername = DBDaos.newInstance().select(TblSysParam.class, "FTP", userNameMagicId); if (selectUsername == null) { SnowExceptionUtil.throwErrorException("请配置FTP用户名!"); } ftpUserName = selectUsername.getParamValueTx(); hashMap.put(userNameMagicId,ftpUserName); TblSysParam selectPassword = DBDaos.newInstance().select(TblSysParam.class, "FTP", passWordMagicId); if (selectPassword == null) { SnowExceptionUtil.throwErrorException("请配置FTP密码!"); } ftpPassword = selectPassword.getParamValueTx(); hashMap.put(passWordMagicId,ftpPassword); return hashMap; } /** * 判断本地路径是否存在,不存在就创建路径 */ public void makeDirs(String localSavePath) { File localFile = new File(localSavePath); if (!localFile.exists()) { localFile.mkdirs(); } } }