1.pom.xml引入jar包
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> <!--csv--> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.4</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.將一個IO流解析,轉化數組形式的集合代碼(csv格式)
/** * sftp服務器 * <b>將一個IO流解析,轉化數組形式的集合<b> * csv文件解析 * @param in * 文件inputStream流 */ public static List<String[]> sftpCsv(InputStream in) { List<String[]> csvList = new ArrayList<String[]>(); if (null != in) { try { InputStreamReader is = new InputStreamReader(in, "UTF-8"); CSVParser csvParser = new CSVParserBuilder().build(); CSVReader reader = new CSVReaderBuilder(is).withCSVParser(csvParser).build(); csvList = reader.readAll(); }catch (UnsupportedEncodingException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } return csvList; }
5.讀取壓縮包zip中的文件
public static void main(String[] args) { ChannelSftp sftp = sftpConnection("118.*.*.*",22,"admin","password"); String path = "/path/"; String filename = "20200623.zip"; try { if (path != null && !"".equals(path)) { sftp.cd(path);//進入所在路徑 } InputStream in = sftp.get(filename); ZipInputStream zin = new ZipInputStream(in); while((zin.getNextEntry())!=null){ List<String[]> strings = sftpCsv(zin); for (String [] s:strings){ for (String ss :s){ System.out.print(ss+","); } System.out.println(); } //也可以直接讀取出來自己處理 /*BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(zin)); String line; while((line = bufferedReader.readLine())!= null){ System.out.println(line); }*/ } in.close(); sftpClose(sftp); sessionClose(); }catch (Exception e){ e.printStackTrace(); } }