package com.jxxgt.ftpdemo.utils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author 咦!一只菜鸡
* @date 2021/5/30 10:11
* @className FtpUtils
* @description ftp工具类
*/
@Component
@PropertySource("classpath:ftp.properties")
public class FtpUtils {
@Value("${ftp.host}")
private String ftpHost;
@Value("${ftp.port}")
private int ftpPort;
@Value("${ftp.username}")
private String ftpUsername;
@Value("${ftp.password}")
private String ftpPassword;
private FTPClient ftpClient;
public static final char SLASH = '/';
public static final char BACKSLASH = '\\';
public boolean init(){
return init(ftpHost,ftpPort,ftpUsername,ftpPassword);
}
/**
* 初始化连接
*
* @return this
*/
public boolean init(String ftpHost,int ftpPort,String ftpUsername,String ftpPassword) {
final FTPClient client = new FTPClient();
client.setControlEncoding("UTF-8");
try {
// 连接ftp服务器
client.connect(ftpHost, ftpPort);
// 登录ftp服务器
client.login(ftpUsername, ftpPassword);
} catch (IOException e) {
// throw new FtpException(e);
}
final int replyCode = client.getReplyCode(); // 是否成功登录服务器
if (false == FTPReply.isPositiveCompletion(replyCode)) {
try {
client.disconnect();
return false;
} catch (IOException e) {
// ignore
}
}
ftpClient = client;
return true;
}
/**
* 改变目录
*
* @param directory 目录
* @return 是否成功
*/
public boolean cd(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
} catch (IOException e) {
// throw new FtpException(e);
}
return flag;
}
/**
* 远程当前目录
*
* @return 远程当前目录
* @since 4.1.14
*/
public String pwd() {
try {
return ftpClient.printWorkingDirectory();
} catch (IOException e) {
// throw new FtpException(e);
}
return "";
}
public List<String> ls(String path) {
final FTPFile[] ftpFiles = lsFiles(path);
final List<String> fileNames = new ArrayList<>();
for (FTPFile ftpFile : ftpFiles) {
fileNames.add(ftpFile.getName());
}
return fileNames;
}
/**
* 遍历某个目录下所有文件和目录,不会递归遍历
*
* @param path 目录
* @return 文件或目录列表
*/
public FTPFile[] lsFiles(String path){
String pwd = null;
if(!StringUtils.isEmpty(path)) {
pwd = pwd();
cd(path);
}
try {
FTPFile[] ftpFiles = ftpClient.listFiles();
if(!StringUtils.isEmpty(pwd)) {
// 回到原目录
cd(pwd);
}
return ftpFiles;
} catch (IOException e) {
// throw new FtpException(e);
}
return null;
}
public boolean mkdir(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
} catch (IOException e) {
// throw new FtpException(e);
}
return flag;
}
/**
* 判断ftp服务器文件是否存在
*
* @param path 文件路径
* @return 是否存在
*/
public boolean existFile(String path) {
FTPFile[] ftpFileArr = new FTPFile[0];
try {
ftpFileArr = ftpClient.listFiles(path);
} catch (IOException e) {
// throw new FtpException(e);
}
if (ftpFileArr!=null&&ftpFileArr.length!=0) {
return true;
}
return false;
}
/**
* 创建指定文件夹及其父目录,从根目录开始创建,创建完成后回到默认的工作目录
*
* @param dir 文件夹路径,绝对路径
*/
public void mkDirs(String dir) {
final String[] dirs = dir.trim().split("[\\\\/]+");
final String now = pwd();
if(dirs.length > 0 && StringUtils.isEmpty(dirs[0])) {
//首位为空,表示以/开头
this.cd(String.valueOf(SLASH));
}
for (int i = 0; i < dirs.length; i++) {
if (!StringUtils.isEmpty(dirs[i])) {
if (false == cd(dirs[i])) {
//目录不存在时创建
mkdir(dirs[i]);
cd(dirs[i]);
}
}
}
// 切换回工作目录
cd(now);
}
/**
* 设置FTP连接模式,可选主动和被动模式
*
* @param mode 模式枚举
* @return this
* @since 4.1.19
*/
public void setMode(String mode) {
switch (mode) {
case "Active": // 主动模式
ftpClient.enterLocalActiveMode();
break;
case "Passive": // 被动模式
ftpClient.enterLocalPassiveMode();
break;
}
}
/**
* 上传文件到指定目录,可选:
*
* <pre>
* 1. path为null或""上传到当前路径
* 2. path为相对路径则相对于当前路径的子路径
* 3. path为绝对路径则上传到此路径
* </pre>
*
*
* @param path 服务端路径,可以为{@code null} 或者相对路径或绝对路径
* @param fileName 文件名
* @param fileStream 文件流
* @return 是否上传成功
*/
public boolean upload(String path, String fileName, InputStream fileStream) {
try {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
if(!StringUtils.isEmpty(path)) {
mkDirs(path);
boolean isOk = cd(path);
if(false == isOk) {
return false;
}
}
return ftpClient.storeFile(fileName, fileStream);
} catch (IOException e) {
// throw new FtpException(e);
}
return false;
}
/**
* 下载文件到输出流
*
* @param path 文件路径
* @param fileName 文件名
* @param out 输出位置
*/
public void download(String path, String fileName, OutputStream out) {
cd(path);
try {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(fileName, out);
} catch (IOException e) {
//
}
}
public static void main(String[] args) throws FileNotFoundException {
FtpUtils ftpUtils = new FtpUtils();
ftpUtils.init("192.168.31.178",21,"ftpUser","jchw1993");
String ftpPath = "/aa"; // ftp文件所在文件夹
// 上传
String fileNameUp = "aaa.zip";
String uploadPath = "D:\\file\\form\\1200401409\\1591235671852.zip";
ftpUtils.setMode("Passive");
File fileUp = new File(uploadPath);
ftpUtils.upload(ftpPath,fileNameUp,new FileInputStream(fileUp));
// 下载
// String fileName = "test2.txt"; // ftp目录中需要下载的文件名
// String dirPath = "D:\\file\\download\\newFile.txt";
// File file = new File(dirPath);
// System.out.println(file.exists());
// OutputStream out = new FileOutputStream(file);
// ftpUtils.download(ftpPath,"test2.txt",out);
}
}
FTP上传下载工具类(应急,过两天完善)
最新推荐文章于 2025-01-13 22:10:28 发布

1万+

被折叠的 条评论
为什么被折叠?



