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(); } }
java连接sftp服务器读取压缩包的文件(例:读取zip中的csv文件返回数组)
原文:https://www.cnblogs.com/xianshen/p/13182730.html