1.pom.xml引入jar包
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
2.連接sftp服務器方法
private static Session sshSession; /** * 連接sftp服務器 * @param host ftp地址 * @param port 端口 * @param userName 賬號 * @param password 密碼 * @return */ public static ChannelSftp sftpConnection(String host,int port, String userName, String password){ JSch jsch = new JSch(); ChannelSftp channelSftp; try { jsch.getSession(userName, host, port); sshSession = jsch.getSession(userName, host, port); sshSession.setPassword(password); Properties properties = new Properties(); properties.put("StrictHostKeyChecking", "no"); sshSession.setConfig(properties); sshSession.connect(); Channel channel = sshSession.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp) channel; }catch (JSchException e){ e.printStackTrace(); throw new RRException("Sftp服務器登錄異常!"); } return channelSftp; }
3.斷開sftp服務方法
/** *@description 退出Sftp服務器登錄 *@return **/ public static void sftpClose(ChannelSftp channelSftp){ if (channelSftp != null) { if (channelSftp.isConnected()){ channelSftp.disconnect(); } } } /** * 關閉session */ public static void sessionClose(){ if (sshSession != null) { if (sshSession.isConnected()){ sshSession.disconnect(); sshSession = null; } } }
4.下載sftp服務器知道路徑的文件到本地方法
/** * 下載sftp文件 * @param sftp * @param newFileName 新文件名稱 * @param path 文件路徑 * @param fileName 文件名稱 * @param downUrl 下載到本地的路徑 * @throws Exception */ public static void downSftpFile(ChannelSftp sftp, String newFileName,String path, String fileName, String downUrl) throws Exception { OutputStream os=null; try { File localFile = new File(downUrl + "/" + newFileName); if (!localFile.getParentFile().exists()) { localFile.getParentFile().mkdirs(); localFile.createNewFile(); } if (path != null && !"".equals(path)) { sftp.cd(path);//進入所在路徑 } os = new FileOutputStream(localFile); sftp.get(path + fileName, os); os.close(); }catch (Exception e){ e.printStackTrace(); } }