- pom文件引入
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
-
代码如下
package com.chinamobilesz.newframework.utils; import com.chinamobilesz.exception.CpException; import com.chinamobilesz.newframework.service.Liquidation.impl.FileRerunServiceImpl; import com.jcraft.jsch.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.apache.commons.net.ftp.FTPFile; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.function.IntPredicate; /** * @Description: sftp客户端连接 * @date: 2020/8/25 9:21 */ @Setter @Getter @NoArgsConstructor public class SftpCilentUtils { private static Logger logger = LogManager.getLogger(SftpCilentUtils.class); private String host; private int port; private String username; private String sftpPw; private String privateKey; private ChannelSftp sftp; private Session session; /** * 构造基于密码认证的sftp对象 */ public SftpCilentUtils(String username, String sftpPw, String host, int port) { this.username = username; this.sftpPw = sftpPw; this.host = host; this.port = port; this.sftp = getChannelSftp(); } /** * 构造基于秘钥认证的sftp对象 */ public SftpCilentUtils(String username, String host, int port, String privateKey) { this.username = username; this.host = host; this.port = port; this.privateKey = privateKey; this.sftp = getChannelSftp(); } /** * 获取session * @param username 用名 * @param host ip * @param port 端口 * @param sftpPw * @param privateKey * @return */ private ChannelSftp getChannelSftp(){ JSch jsch = new JSch(); try { if (privateKey != null) jsch.addIdentity(privateKey);// 设置私钥 if (this.port <= 0){ this.session = jsch.getSession(this.username,this.host);//使用默认端口22 }else{ this.session = jsch.getSession(this.username,this.host,this.port); } this.session.setConfig("StrictHostKeyChecking","no");//首次登陆询问 this.session.setPassword(this.sftpPw); this.session.connect(300000);// 登陆超时时间30s Channel channel = this.session.openChannel("sftp"); channel.connect(10000); this.sftp = (ChannelSftp) channel; logger.info("获取sftp连接成功。。。。"); System.err.println("获取sftp连接成功"); } catch (JSchException e) { logger.error("获取sftp连接失败:",e); throw new CpException(String.format("获取sftp连接异常 %s",e.getMessage())); } return this.sftp; } /** * 退出sftp连接 */ public void logout(){ if (this.sftp != null) { if (this.sftp.isConnected()) { this.sftp.disconnect(); logger.info("sftp通道关闭成功!"); } } if (this.session != null) { if (this.session.isConnected()) { this.session.disconnect(); logger.info("sftpSession关闭成功"); } } } /** * 下载文件到本地 * @param serverFileName 服务器文件名称 * @param localDires 服务器本地临时目录 * @param serverDownLoadPath sftp下载目录 */ public void sftpFileDownload(String serverFileName, String localDires, String serverDownLoadPath){ String strFilePath = localDires + File.separator + serverFileName; BufferedOutputStream outStream = null; try { //进入服务器指定的文件夹 this.sftp.cd(serverDownLoadPath); outStream = new BufferedOutputStream(new FileOutputStream(strFilePath)); //下载文件 this.sftp.get(serverFileName,outStream); logger.info(String.format("sftp下载%s文件成功",serverFileName)); } catch (Exception e) { logger.error("文件下载失败{}",e); throw new CpException(String.format("sftp下载文件失败,路径为%s,文件名为%s",serverDownLoadPath,serverFileName)); }finally { if (null != outStream) { try { outStream.flush(); outStream.close(); } catch (IOException e) { logger.error("关闭outStream异常",e); } } } } /** * 下载文件夹 * @param localDirectoryPath 本地临时目录 * @param remoteDirectory sftp服务器目录 * @param fileNameList * @return */ public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory,List<String> fileNameList) { try { String fileName = new File(remoteDirectory).getName(); localDirectoryPath = localDirectoryPath + fileName + File.separator; new File(localDirectoryPath).mkdirs(); this.sftp.cd(remoteDirectory); Vector<ChannelSftp.LsEntry> fileAndFolderList = this.sftp.ls(remoteDirectory); String finalLocalDirectoryPath = localDirectoryPath; //如果下载的不是目录就直接下载文件 fileAndFolderList.forEach(f ->{ if (!f.getAttrs().isDir()) { fileNameList.forEach(name -> { if (f.getFilename().equals(name)){ this.sftpFileDownload(f.getFilename(), finalLocalDirectoryPath,remoteDirectory); } }); } }); //如果下载的是目录,就递归分目录下载文件 for (int currentFile = 0; currentFile < fileAndFolderList.size(); currentFile++) { String filename = fileAndFolderList.get(currentFile).getFilename(); if (fileAndFolderList.get(currentFile).getAttrs().isDir()) { if (filename.equals(".") || filename.equals("..")) continue; String strremoteDirectoryPath = remoteDirectory + "/" + filename; downLoadDirectory(localDirectoryPath, strremoteDirectoryPath,fileNameList); } } } catch (Exception e) { e.printStackTrace(); logger.info("下载文件夹失败"); return false; } return true; } /*** * 上传单个sftp文件 * @param localFile 当地文件 * @param romotUpLoadePath 上传服务器路径 - 应该以/结束 * */ public void uploadFile(File localFile, String romotUpLoadePath) { BufferedInputStream inStream = null; boolean success = false; try { this.sftp.cd(romotUpLoadePath);// 改变工作路径 inStream = new BufferedInputStream(new FileInputStream(localFile)); logger.info(localFile.getName() + "开始上传....."); this.sftp.put(inStream, localFile.getName()); logger.info(String.format("%s文件上传成功",localFile.getName())); } catch (Exception e) { logger.error("上传失败:",e); throw new CpException(String.format("%s文件上传失败",localFile.getName())); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /*** * @sftp上传文件夹 * @param localDirectory * 当地文件夹 *@param defaultPath * 上传sFtp默认的根目录 * @param remoteDirectoryPath * Ftp 服务器路径 以目录"/"结束 * */ public void uploadDirectory(String localDirectory, String defaultPath, String remoteDirectoryPath) { File src = new File(localDirectory); try { //创建目录 try { sftp.cd(defaultPath); } catch (SftpException e) { sftp.mkdir(defaultPath); sftp.cd(defaultPath); } remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/"; sftp.mkdir(remoteDirectoryPath); sftp.cd(remoteDirectoryPath); } catch (Exception e) { e.printStackTrace(); logger.info(remoteDirectoryPath + "目录创建失败"); } File[] allFile = src.listFiles(); for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (!allFile[currentFile].isDirectory()) { String srcName = allFile[currentFile].getPath().toString(); uploadFile(new File(srcName), remoteDirectoryPath); } } for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (allFile[currentFile].isDirectory()) { // 递归 uploadDirectory(allFile[currentFile].getPath().toString(), defaultPath, remoteDirectoryPath); } } } /*** * sftp下载文件csv转excel * @param remoteFileName 待下载文件名称 * @param localDires 下载到当地那个路径下 * @param remoteDownLoadPath remoteFileName所在的路径 * */ public boolean downloadFileCsvToExcel(String remoteFileName, String localDires, String remoteDownLoadPath) { try { sftp.cd(remoteDownLoadPath); logger.info("下载的ftp路径:"+remoteDownLoadPath); logger.info(remoteFileName + "开始获取ftp文件流...."); InputStream inputStream = sftp.get(remoteFileName); logger.info(remoteFileName +"获取ftp文件流----->",inputStream); if (inputStream == null) throw new Exception("获取ftp文件流为空"); logger.info("开始解析文件"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader brs = new BufferedReader(inputStreamReader); //转excel文件 String xlsFileName = remoteFileName.replaceAll(remoteFileName.substring(remoteFileName.indexOf(".") + 1), "xlsx"); String strFilePath = localDires + File.separator + xlsFileName; ExcelUtils.exportExcel(strFilePath,brs); //输入流关闭资源 inputStream.close(); inputStreamReader.close(); brs.close(); logger.info("{}导出excel成功", remoteFileName); } catch (Exception e) { logger.error("{}下载失败{}", remoteFileName, e); return false; } return true; } public static void main(String[] args) { SftpCilentUtils sftpCilentUtils = new SftpCilentUtils("sftp","sftp123","127.0.0.1",22); List<String> fileNamelist= new ArrayList <>(); fileNamelist.add("test4.xlsx"); fileNamelist.add("tstt.xlsx"); fileNamelist.add("test2.xlsx"); fileNamelist.add("text3.xlsx"); //下载单个文件 // sftpCilentUtils.sftpFileDownload("文件名","本地路径","sftp路径"); //下载文件夹 // sftpCilentUtils.downLoadDirectory("本地路径","sftp路径",fileNamelist); //单个文件上传 // sftpCilentUtils.uploadFile(new File("本地文件全路径"),"sftp目录"); //上传文件夹 //sftpCilentUtils.uploadDirectory("本地文件夹路径","sftp临时路径","sftp临时路径"); //sftpCilentUtils.downloadFileCsvToExcel("sftp文件","本地目录","sftp目录"); sftpCilentUtils.logout(); } }
java sftp工具类
最新推荐文章于 2024-04-21 00:52:57 发布