1.在pom.xml文件中引入JAR包:
com.jcraft
jsch
0.1.54
2.编写工具类SftpUtils.java,该工具类可直接拷贝使用
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
public class SftpUtils {
private Logger logger = LoggerFactory.getLogger(SftpUtils.class);
/**
* 连接sftp服务器
*
* @param host
* 主机
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
} catch (Exception e) {
e.printStackTrace();
sftp = null;
}
return sftp;
}
public ChannelSftp connectSftp(Session sshSession) {
ChannelSftp sftp = null;
try {
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
sftp = null;
}
return sftp;
}
public void exec(Session sshSession,String command) {
ChannelExec channelExec = null;
try {
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("exec");
channelExec = (ChannelExec) channel;
channelExec.setCommand(command);
channelExec.connect();
} catch (Exception e) {
e.printStackTrace();
channelExec = null;
}finally {
channelExec.disconnect();
}
}
public Session getSession(String host, int port, String username, String password) {
Session sshSession = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
} catch (Exception e) {
e.printStackTrace();
}
return sshSession;
}
/**
* 上传文件
*
* @param directory
* 上传的目录
* @param uploadFile
* 要上传的文件
* @param sftp
*/
public String upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
if(!directory.equals("")){
sftp.cd(directory);
}
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
System.out.println("上传完成");
sftp.disconnect();
sftp.getSession().disconnect();
return "传输成功";
} catch (Exception e) {
e.printStackTrace();
sftp.disconnect();
try {
sftp.getSession().disconnect();
} catch (JSchException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return "传输失败,请检查配置!";
}
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
* @param sftp
*/
public void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
sftp.disconnect();
sftp.getSession().disconnect();
System.out.println("download ok,session closed");
} catch (Exception e) {
sftp.disconnect();
try {
sftp.getSession().disconnect();
} catch (JSchException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
public List read(String directory, String readFile, ChannelSftp sftp,String charSetName) {
List stringlist = new ArrayList<>();
InputStream inputStream = null;
try {
sftp.cd(directory);
inputStream = sftp.get(readFile);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,charSetName));
String line = null;
line = br.readLine();
while (line != null) {
stringlist.add(line);
line = br.readLine(); // 一次读入一行数据
}
br.close();
}
catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringlist;
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp)
throws SftpException {
return sftp.ls(directory);
}
/**
* 将输入流的数据上传到sftp作为文件
*
* @param directory
* 上传到该目录
* @param sftpFileName
* sftp端文件名
* @param input
* 输入流
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, InputStream input,ChannelSftp sftp) throws SftpException, JSchException {
try {
sftp.cd(directory);
} catch (SftpException e) {
logger.warn("directory is not exist");
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
if(sftp.isConnected()) {
sftp.disconnect();
}
if (sftp.getSession().isConnected()) {
sftp.getSession().disconnect();
}
logger.info("file:{"+sftpFileName+"} is upload successful");
}
3.调用JSCH工具类方法获取远程服务器中.txt后缀的文件内容:
public List readFile(String host,int port,String userName,String passWord,String srcDirectory,String bakDirectory,String filterKey){
List students = new ArrayList<>();
SftpUtils sf = new SftpUtils();
Session session = sf.getSession(host, port, userName, passWord);
ChannelSftp sftp = sf.connectSftp(session); //连接
String date = "20180601";
String bakFolder = bakDirectory + "/" + date; //备份目录
SftpATTRS isExist = null;
try {
isExist = sftp.stat(bakFolder);//判断备份目录是否存在,不存在则创建
if(isExist==null){
sftp.mkdir(bakFolder);
}
} catch (SftpException e) {
}
try {
sftp.cd(srcDirectory);//进入源目录
Vector vector = sftp.ls(filterFileKey);//获取该目录下匹配的文件
logger.info("ls " + filterKey);
logger.info("file total num " + vector.size());
for (ChannelSftp.LsEntry lsEntry:vector) {
if(lsEntry != null){
String filleName = lsEntry.getFilename();
logger.info("read the file "+filleName );
try {
List list = sf.read(srcDirectory, filleName, sftp,"GBK");
for (int i = 0; i < list.size(); i++) {
String content = list.get(i);
if(content!=null) {
Student student = new Student();
String[] args = content.split("\\|");
student.setId(args[0]);
student.setName(args[1]);
students.add(student);
}
}
//移动文件到备份目录
String command = "mv "+(srcDirectory + "/" + filleName) + " " + bakDirectory + "/" + date + "/";
logger.info(command);
sf.exec(session,command);
}catch (Exception ex){
ex.printStackTrace();
}
}
}
} catch (SftpException e) {
e.printStackTrace();
}finally {
sftp.disconnect();
try {
sftp.getSession().disconnect();
} catch (JSchException e) {
e.printStackTrace();
}
}
return students;
}