本文使用FTPClient对FTP进行文件操作,FTPClient工具需要添加Maven依赖。
<!-- commons-net FTP工具类-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
在测试文件上传过程中,发现中文名称的文件上传到FTP服务器乱码。
问题解决的思路是设置上传文件名称的编码格式为UTF-8,那么怎么设置呢?为了一劳永逸的方式解决文件上传下载均不会乱码,在FTP登录的时候设置字符编码,这样就不用担心乱码问题了。下面看代码
public static FTPClient connectFTP(String ip, int port, String uname, String pwd) throws IOException {
FTPClient ftpClient = new FTPClient();
// 优先设置编码格式,避免中文乱码
ftpClient.setAutodetectUTF8(true);
ftpClient.setCharset(CharsetUtil.UTF_8);
ftpClient.setControlEncoding(CharsetUtil.UTF_8.name());
ftpClient.connect(ip, port);
boolean login = ftpClient.login(uname, pwd);
if (!login) {
throw new BusinessException("ftp连接失败,请检查配置");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setBufferSize(DEFAULT_BUFFER_SIZE);
return ftpClient;
}
其中CharsetUtil使用的依赖包是netty的依赖,需要在Maven添加netty依赖。
<!-- netty-common -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
<version>4.1.77.Final</version>
</dependency>
下面提供一个简单的FTP工具类
import xxx.xxx.xxx.BusinessException;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author
* @date 2022/8/2 15:53
* @description
*/
@Slf4j
public class FtpUtils {
private static final int DEFAULT_BUFFER_SIZE = 4096;
/**
* 上传文件
*
* @param input 输入流
* @param uploadPath 保存路径
* @param fileName 文件名(包含格式后缀)
* @param ftpClient FTP客户端连接
* @throws IOException
*/
public static void upload(InputStream input, String uploadPath, String fileName, FTPClient ftpClient) {
try {
// 判断路径是否存在,不存在则新建
checkFTPPath(ftpClient, uploadPath);
// 保存文件到路径
ftpClient.storeFile(fileName, input);
log.info("您的文件【{}】上传成功。", fileName);
} catch (IOException e) {
log.error("FTP上传文件时出错", e);
throw new BusinessException("sys.file.fail");
} finally {
// 关闭连接
IOUtils.closeQuietly(input);
closeFTP(ftpClient);
}
}
/**
* 上传文件
*
* @param input 输入流
* @param uploadPath 保存路径
* @param fileName 文件名(包含格式后缀)
* @param ip
* @param port
* @param uname
* @param pwd
* @throws IOException
*/
public static void upload(InputStream input, String uploadPath, String fileName, String ip, int port, String uname, String pwd) {
FTPClient ftpClient = new FTPClient();
try {
// 获取FTP客户端
ftpClient = connectFTP(ip, port, uname, pwd);
// 判断路径是否存在,不存在则新建
checkFTPPath(ftpClient, uploadPath);
// 保存文件到路径
ftpClient.storeFile(fileName, input);
log.info("您的文件【{}】上传成功。", fileName);
} catch (IOException e) {
log.error("FTP上传文件时出错", e);
throw new BusinessException("sys.file.fail");
} finally {
// 关闭连接
IOUtils.closeQuietly(input);
closeFTP(ftpClient);
}
}
/**
* 删除文件
*
* @param path 文件地址
* @param ftpClient FTP客户端
* @return
* @throws IOException
*/
public static Boolean deleteFile(String path, FTPClient ftpClient) {
Boolean flag = false;
try {
//删除
if (ftpClient != null) {
flag = ftpClient.deleteFile(path);
log.info("您的文件【{}】删除成功。", path);
}
} catch (IOException e) {
log.error("FTP删除文件时出错", e);
throw new BusinessException("sys.file.delete.fail");
} finally {
closeFTP(ftpClient);
}
return flag;
}
/**
* 删除文件
*
* @param path 文件地址
* @param ip
* @param port
* @param uname
* @param pwd
* @return
* @throws IOException
*/
public static Boolean deleteFile(String path, String ip, int port, String uname, String pwd) {
Boolean flag = false;
FTPClient ftpClient = new FTPClient();
try {
// 获取FTP客户端
ftpClient = connectFTP(ip, port, uname, pwd);
//删除
if (ftpClient != null) {
flag = ftpClient.deleteFile(path);
log.info("您的文件【{}】删除成功。", path);
}
} catch (IOException e) {
log.error("FTP删除文件时出错", e);
throw new BusinessException("sys.file.delete.fail");
} finally {
closeFTP(ftpClient);
}
return flag;
}
/**
* 删除目录
*
* @param path 目录地址
* @param ftpClient FTP客户端
* @return
* @throws IOException
*/
public static Boolean deleteDirectory(String path, FTPClient ftpClient) {
Boolean flag = false;
try {
//删除
if (ftpClient != null) {
flag = ftpClient.removeDirectory(path);
log.info("您的目录【{}】删除成功。", path);
}
} catch (IOException e) {
log.error("FTP删除目录时出错", e);
throw new BusinessException("sys.file.delete.fail");
} finally {
closeFTP(ftpClient);
}
return flag;
}
/**
* 删除目录
*
* @param path 目录地址
* @param ip
* @param port
* @param uname
* @param pwd
* @return
* @throws IOException
*/
public static Boolean deleteDirectory(String path, String ip, int port, String uname, String pwd) {
Boolean flag = false;
FTPClient ftpClient = new FTPClient();
try {
// 获取FTP客户端
ftpClient = connectFTP(ip, port, uname, pwd);
//删除
if (ftpClient != null) {
flag = ftpClient.removeDirectory(path);
log.info("您的目录【{}】删除成功。", path);
}
} catch (IOException e) {
log.error("FTP删除目录时出错", e);
throw new BusinessException("sys.file.delete.fail");
} finally {
closeFTP(ftpClient);
}
return flag;
}
/**
* 从ftp上下载
*
* @param output 输出流
* @param remoteFile 文件路径
* @param ftpClient FTP客户端
*/
public static void download(OutputStream output, String remoteFile, FTPClient ftpClient) {
try {
ftpClient.enterLocalPassiveMode();
ftpClient.retrieveFile(remoteFile, output);
output.flush();
log.info("您的文件【{}】下载成功。", remoteFile);
} catch (Exception e) {
log.error("下载文件出错:", e);
} finally {
IOUtils.closeQuietly(output);
closeFTP(ftpClient);
}
}
/**
* 从ftp上下载
*
* @param output 输出流
* @param remoteFile 文件路径
* @param ip
* @param port
* @param uname
* @param pwd
*/
public static void download(OutputStream output, String remoteFile, String ip, int port, String uname, String pwd) {
FTPClient ftpClient = new FTPClient();
try {
// 获取FTP客户端
ftpClient = connectFTP(ip, port, uname, pwd);
ftpClient.enterLocalPassiveMode();
ftpClient.retrieveFile(remoteFile, output);
output.flush();
log.info("您的文件【{}】下载成功。", remoteFile);
} catch (Exception e) {
log.error("下载文件出错:", e);
} finally {
IOUtils.closeQuietly(output);
closeFTP(ftpClient);
}
}
/**
* 连接FTP服务器
*
* @param ip
* @param port
* @param uname
* @param pwd
* @return
* @throws IOException
*/
public static FTPClient connectFTP(String ip, int port, String uname, String pwd) throws IOException {
FTPClient ftpClient = new FTPClient();
// 优先设置编码格式,避免中文乱码
ftpClient.setAutodetectUTF8(true);
ftpClient.setCharset(CharsetUtil.UTF_8);
ftpClient.setControlEncoding(CharsetUtil.UTF_8.name());
ftpClient.connect(ip, port);
boolean login = ftpClient.login(uname, pwd);
if (!login) {
throw new BusinessException("ftp连接失败,请检查配置");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setBufferSize(DEFAULT_BUFFER_SIZE);
return ftpClient;
}
/**
* 关闭连接
*
* @param ftpClient
*/
public static void closeFTP(FTPClient ftpClient) {
if (ftpClient != null) {
try {
ftpClient.disconnect();
} catch (IOException e) {
log.error("关闭FTP连接出错", e);
throw new BusinessException("sys.file.fail");
}
}
}
/**
* 校验路径是否存在,不存在则新建
*
* @param ftpClient
* @param uploadPath
* @throws IOException
*/
private static void checkFTPPath(FTPClient ftpClient, String uploadPath) throws IOException {
//判断路径是否存在,不存在则新建
if (uploadPath != null) {
String[] paths = uploadPath.split("/");
StringBuffer tempPath = new StringBuffer();
for (String path : paths) {
if ((path != null) && (!"".equals(path.trim()))) {
String temp = tempPath.append("/").append(path.trim()).toString();
if ((!ftpClient.changeWorkingDirectory(temp)) && (ftpClient.makeDirectory(temp))) {
ftpClient.changeWorkingDirectory(temp);
}
}
}
}
}
}