maven:
<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>
package com.tmnch.tmnchpinan.service;
import com.jcraft.jsch.*;
import org.junit.Test;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.zip.*;
/**
* * Description:
* *
* * @author thw
* * @date 2020/9/23 15:15
*
*/
public class ftpServices {
private static Session sshSession;
@Test
public void run() {
String path = "/bin/"; //sftp路径
String filename = "test.zip";//zip文件名
ZipEntry zipEntry = null;
try {
//连接sftp
ChannelSftp sftp = sftpConnection("192.1.1.1", 22, "root", "root);
if (path != null && !"".equals(path)) {
sftp.cd(path);
}
InputStream in = sftp.get(filename);
ZipInputStream zin = new ZipInputStream(in);
while ((zipEntry = zin.getNextEntry()) != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(zin));
String line = null;
String fileNmae = null;
String[] fileNmaeLIst = null;
String tableNmae = null;
if ((line = bufferedReader.readLine()) != null) {
fileNmae = zipEntry.getName();//txt路径名
// fileNmaeLIst = fileNmae.split("/");
//tableNmae = fileNmaeLIst[2];//表名
//System.out.println(fileNmae);
//System.out.println(tableNmae);
}
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
in.close();
sftpClose(sftp);
sessionClose();
} catch (Exception e) {
e.printStackTrace();
}
}
//连接sftp
public static ChannelSftp sftpConnection(String host, int port, String userName, String password) throws Exception {
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();
}*/
return channelSftp;
}
/**
* @return
* @description 退出Sftp服务器登录
**/
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;
}
}
}
}