public class FtpUtil {
Integer time = 7200000;
private static final Logger log = LoggerFactory.getLogger(FtpUtil.class);
public FTPClient ftpClient = null;
public FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort)
throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
ftpClient.setDataTimeout(time); // 设置传输超时时间
ftpClient.setConnectTimeout(time); // 连接超时
// 设置编码格式为二进制编码,防止文件损坏
try {
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
log.error("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
}
}catch (Exception e) {
throw new RuntimeException("FTP的端口错误,请正确配置。",e);
}
return ftpClient;
}
/**
*
* 上传文件
* @param ftpClient ftp客户端
* @param parentPath 根目录
* @param dirPath 文件目录
* @param fileName 文件名
* @param originfilename 待上传文件路径 绝对路径
* @return
* @throws Exception
*/
public boolean uploadFile(FTPClient ftpClient, String parentPath, String dirPath, String fileName, String originfilename) throws Exception {
log.info("开始上传 ftp 文件,ftp目录:{},ftp 文件夹:{},上传文件名:{},本地文件路径:{}",parentPath,dirPath,fileName,originfilename);
InputStream inputStream = new FileInputStream(new File(originfilename));
return uploadFile(ftpClient, parentPath, dirPath,fileName,inputStream);
}
/**
* 上传文件
* @param ftpClient ftp客户端
* @param parentPath 根目录
* @param dirPath 文件目录
* @param fileName 文件名
* @param inputStream 待上传文件流
* @return
* @throws Exception
*/
public boolean uploadFile(FTPClient ftpClient, String parentPath, String dirPath, String fileName, InputStream inputStream)
throws Exception {
boolean flag = false;
try {
log.info("开始上传文件.....");
this.ftpClient = ftpClient;
ftpClient.enterLocalPassiveMode();
// 保持连接
ftpClient.setKeepAlive(true);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//判断FPT目标文件夹时候存在不存在则创建
if (!changeWorkingDirectory(parentPath)) {
// 创建远程文件夹
createDirecroty(parentPath);
}
// 进入到公共目录
changeWorkingDirectory(parentPath);
// 创建文件夹
if (!changeWorkingDirectory(dirPath)) {
// 创建远程文件夹
makeDirectory(dirPath);
}
// 进入到子目录
changeWorkingDirectory(dirPath);
// 文件上传
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
log.info("上传文件成功");
} catch (Exception e) {
log.error("上传文件失败", e);
throw new RuntimeException("上传文件失败", e);
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (Exception e) {
throw new RuntimeException("上传文件失败", e);
}
}
}
return flag;
}
// 改变目录路径
public boolean changeWorkingDirectory(String directory) throws Exception {
boolean flag = true;
try {
// flag = getDefaultFtpClient().changeWorkingDirectory(directory);
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
log.info("进入文件夹" + directory + " 成功!\"");
} else {
log.info("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (Exception e) {
throw new RuntimeException("改变目录路径失败", e);
}
return flag;
}
// 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public boolean createDirecroty(String remote) throws Exception {
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("UTF-8"));
path = path + "/" + subDirectory;
log.info("path:{},subDirectory:{}", path, subDirectory);
// false表示当前文件夹下没有文件
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
log.error("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
}
// 判断ftp服务器文件是否存在
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
// FTPFile[] ftpFileArr = getDefaultFtpClient().listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
// 创建目录
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
// flag = getDefaultFtpClient().makeDirectory(dir);
flag = ftpClient.makeDirectory(dir);
if (flag) {
log.info("创建文件夹" + dir + " 成功!");
} else {
log.error("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
throw new RuntimeException("创建文件夹失败", e);
}
return flag;
}
/**
* * 下载文件 *
*
* @param pathName FTP服务器文件目录 *
* @param fileName 文件名称 *
* @param savePath 下载后的文件路径 *
*/
public boolean downloadFile(FTPClient ftpClient, String pathName, String fileName, String savePath) throws Exception {
boolean flag;
OutputStream os = null;
try {
log.info("开始下载文件");
this.ftpClient = ftpClient;
// 切换FTP目录
changeWorkingDirectory(pathName);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] ftpFiles = ftpClient.listFiles();
log.info("ftpFiles.length:{}",ftpFiles.length);
for (FTPFile file : ftpFiles) {
if (fileName.equalsIgnoreCase(file.getName())) {
File folder = new File(savePath);
// 判断文件夹是否存在
if (!folder.exists()) {
folder.mkdirs();
}
os = new FileOutputStream(savePath + "/" + fileName);
log.info("lzdebt:下载中");
ftpClient.retrieveFile(file.getName(), os);
os.close();
log.info("lzdebt:下载结束");
}
}
ftpClient.logout();
flag = true;
// 解压 ZIP 文件
IOUtils.zipUncompress(savePath + "/" + fileName,savePath);
log.info("下载文件成功");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("下载文件失败", e);
}
}
if (null != os) {
try {
os.close();
} catch (Exception e) {
throw new RuntimeException("下载文件失败", e);
}
}
}
return flag;
}
/**
* * 删除文件 *
*
* @param pathName FTP服务器保存目录 *
* @param fileName 要删除的文件名称 *
* @return
*/
public boolean deleteFile(FTPClient ftpClient, String pathName, String fileName) throws Exception {
boolean flag;
try {
log.info("开始删除文件");
this.ftpClient = ftpClient;
// 切换FTP目录
ftpClient.changeWorkingDirectory(pathName);
ftpClient.dele(fileName);
ftpClient.logout();
flag = true;
log.info("删除文件成功");
} catch (Exception e) {
throw new Exception("删除文件失败", e);
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new Exception("删除文件失败", e);
}
}
}
return flag;
}
}