依赖
<!--SFTP模块-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
sftp
package com.jgzh.pay.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.jcraft.jsch.*;
import com.jgzh.pay.domain.ExcelConfig;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.*;
@Slf4j
public class SFTPUtils {
private String host;
private String password;
private String username;
private int port = 22;
private ChannelSftp sftp = null;
private Session sshSession = null;
public SFTPUtils() {
}
public SFTPUtils(String host, int port, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
this.port = port;
connect();
}
public SFTPUtils(ExcelConfig excelConfig) {
this.host = excelConfig.getHost();
this.username = excelConfig.getUsername();
this.password = excelConfig.getPassword();
this.port = excelConfig.getPort();
connect();
}
public SFTPUtils(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
connect();
}
public void connect() {
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + " success.");
} catch (Exception e) {
e.printStackTrace();
}
}
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
System.out.println("sftp is closed already");
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
System.out.println("sshSession is closed already");
}
}
}
public List<String> batchDownLoadFile(String remotePath, String localPath,
String fileFormat, String fileEndFormat, boolean del) {
List<String> filenames = new ArrayList<String>();
try {
Vector v = listFiles(remotePath);
if (v.size() > 0) {
System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
Iterator it = v.iterator();
while (it.hasNext()) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: fileEndFormat.trim();
if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
if (filename.startsWith(fileFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
if (filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
System.out.println("download file is success:remotePath=" + remotePath
+ "and localPath=" + localPath + ",file size is"
+ v.size());
} catch (SftpException e) {
e.printStackTrace();
}
return filenames;
}
public List<File> batchDownLoadFileInputStream(String remotePath){
List<File> fileList = CollUtil.newArrayList();
try {
Vector v = listFiles(remotePath);
if (!v.isEmpty()) {
log.info("本次处理文件个数不为零,开始压缩...");
Iterator it = v.iterator();
while (it.hasNext()) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
File file = downloadFileInputStream(remotePath, filename);
fileList.add(file);
}
}
}
} catch (SftpException e) {
e.printStackTrace();
}
return fileList;
}
public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileOutputStream fieloutput = null;
try {
File file = new File(localPath + localFileName);
mkdirs(localPath + localFileName);
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
System.out.println("===DownloadFile:" + remoteFileName + " success from sftp.");
return true;
} catch (FileNotFoundException | SftpException e) {
e.printStackTrace();
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public File downloadFileInputStream(String remotePath, String remoteFileName) {
InputStream fileInputStream = null;
File file = null;
try {
fileInputStream = sftp.get(remotePath + remoteFileName);
file = FileUtil.writeFromStream(fileInputStream,new File(remoteFileName),true);
log.info("文件压缩成功:{}",remoteFileName);
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (null != fileInputStream) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileInputStream in = null;
try {
createDir(remotePath);
File file = new File(localPath + localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public boolean bacthUploadFile(String remotePath, String localPath,
boolean del) {
try {
connect();
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1) {
if (this.uploadFile(remotePath, files[i].getName(),
localPath, files[i].getName())
&& del) {
deleteFile(localPath + files[i].getName());
}
}
}
System.out.println("upload file is success:remotePath=" + remotePath
+ "and localPath=" + localPath + ",file size is "
+ files.length);
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
this.disconnect();
}
return false;
}
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
boolean rs = file.delete();
if (rs)
System.out.println("delete file success from local.");
else System.out.println("delete file failed from local.");
return rs;
}
public boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
public void deleteSFTP(String directory, String deleteFile) {
try {
sftp.rm(directory + deleteFile);
System.out.println("delete file success from sftp.");
} catch (Exception e) {
e.printStackTrace();
}
}
public void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists()) {
f.mkdirs();
}
}
public Vector listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
}
ftp
package com.lianfu.heatcompany.hoobok;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.MalformedURLException;
public class FtpUtils {
public String hostname;
public Integer port;
public String username;
public String password;
public FTPClient ftpClient = null;
public FtpUtils(String hostname, Integer port, String username, String password) {
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
}
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
System.out.println("connecting...ftp服务器:" + this.hostname + ":" + this.port);
ftpClient.connect(hostname, port);
ftpClient.login(username, password);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("connect failed...ftp服务器:" + this.hostname + ":" + this.port);
}
System.out.println("connect successfu...ftp服务器:" + this.hostname + ":" + this.port);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean uploadFile(String pathname, String fileName, String originfilename) {
boolean flag = false;
InputStream inputStream = null;
try {
System.out.println("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
System.out.println("上传文件成功");
} catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public boolean uploadFile(String pathname, String fileName, InputStream inputStream) {
boolean flag = false;
try {
System.out.println("开始上传文件");
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
System.out.println("上传文件成功");
} catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
System.out.println("进入文件夹" + directory + " 成功!");
} else {
System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
public boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
System.out.println("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
if (end <= start) {
break;
}
}
}
return success;
}
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
System.out.println("创建文件夹" + dir + " 成功!");
} else {
System.out.println("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public boolean downloadFile(String pathname, String filename, String localpath) {
boolean flag = false;
OutputStream os = null;
try {
System.out.println("开始下载文件");
initFtpClient();
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles) {
if (filename.equalsIgnoreCase(file.getName())) {
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
flag = true;
System.out.println("下载文件成功");
} catch (Exception e) {
System.out.println("下载文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
public boolean deleteFile(String pathname, String filename) {
boolean flag = false;
try {
System.out.println("开始删除文件");
initFtpClient();
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
System.out.println("删除文件成功");
} catch (Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
public static void main(String[] args) {
FtpUtils ftp = new FtpUtils("地址", 21, "用户名", "密码");
ftp.uploadFile("", "100001_20200709.txt", "D://保存位置");
System.out.println("ok");
}
}