封装好的ftpUtil工具
1.FTPUtil.java
package com.esinhai.common.utils;
import com.esinhai.common.entity.CommonException;
import com.esinhai.common.enums.ErrorCode;
import com.esinhai.epm.api.resp.FtpFileParams;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by geely
*/
@Component
public class FTPUtil {
private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);
public static boolean uploadFile(List<File> files, String remotePath) throws Exception {
logger.info("开始连接ftp服务器");
FTPClient ftpClient = connectServer(
PropertiesUtil.getProperty("ftp.ip"),
PropertiesUtil.getProperty("ftp.port"),
PropertiesUtil.getProperty("ftp.user"),
PropertiesUtil.getProperty("ftp.password"));
ftpClient.enterLocalActiveMode();
changeWork(ftpClient, remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalActiveMode();
List<String> tar = encryptFile(files);
boolean result = uploadFile(ftpClient, tar);
FileUploadUtil.delete(tar);
logger.info("开始连接ftp服务器,结束上传");
return result;
}
public static boolean downloadFile(List<FtpFileParams> list) throws Exception {
logger.info("开始连接ftp服务器");
FTPClient ftpClient = connectServer(
PropertiesUtil.getProperty("ftp.ip"),
PropertiesUtil.getProperty("ftp.port"),
PropertiesUtil.getProperty("ftp.user"),
PropertiesUtil.getProperty("ftp.password"));
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalActiveMode();
createDir(list);
boolean result = downloadFile(ftpClient, list);
decryptedFile(list);
FileUploadUtil.delete(list.stream().map(e -> {
try {
return ResourcePathUtil.getResourceRootPath() + "/temp/" + e.getFileName();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return "";
}).collect(Collectors.toList()));
logger.info("开始连接ftp服务器,结束下载");
return result;
}
private static void decryptedFile(List<FtpFileParams> list) throws FileNotFoundException {
for(FtpFileParams ftpFileParams : list) {
String temp = ResourcePathUtil.getResourceRootPath() + "/temp/" + ftpFileParams.getFileName();
MyFileEncryptor.decryptedFile(temp, ftpFileParams.getLocalPath() + ftpFileParams.getFileName());
}
}
public static boolean downloadFile(FTPClient ftpClient, List<FtpFileParams> list) throws Exception {
boolean flag ;
OutputStream os = null;
try {
for(FtpFileParams ftpFileParams : list) {
try{
String temp = ResourcePathUtil.getResourceRootPath() + "/temp/" + ftpFileParams.getFileName();
os = new FileOutputStream(temp);
ftpClient.retrieveFile(ftpFileParams.getFtpPath(), os);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
flag = true;
} catch (Exception e) {
throw new Exception(e);
} finally {
closeCon(ftpClient);
}
return flag;
}
private static void changeWork(FTPClient ftpClient, String remotePath) throws IOException, CommonException {
//如果路径是以/开头,则去掉/
if (remotePath.indexOf("/") == 0) {
remotePath = remotePath.substring(1);
}
String work = remotePath.substring(0, remotePath.indexOf("/") == -1 ? remotePath.length() : remotePath.indexOf("/"));
if (!ftpClient.changeWorkingDirectory(work)) {
boolean status = ftpClient.makeDirectory(work);
if (!status) {
throw new CommonException(ErrorCode.FTP_CREATE_DIR_ERROR);
}
status = ftpClient.changeWorkingDirectory(work);
if (!status) {
throw new CommonException(ErrorCode.FTP_CHANGE_WORK_ERROR);
}
String next = remotePath.replace(work, "");
if (!"".equals(next) && !"/".equals(next))
changeWork(ftpClient, remotePath.replace(work, ""));
} else {
String next = remotePath.replace(work, "");
if (!"".equals(next) && !"/".equals(next))
changeWork(ftpClient, remotePath.replace(work, ""));
}
}
private static List<String> encryptFile(List<File> files) throws FileNotFoundException {
String path = ResourcePathUtil.getResourceRootPath() + "/temp/";
File create = new File(path);
if(!create.exists()){
create.mkdirs();
}
List<String> result = new ArrayList<>();
for(File file : files){
String srcpath = file.getPath();
String tarfile = ResourcePathUtil.getResourceRootPath() + "/temp/" + srcpath.substring(srcpath.lastIndexOf(System.getProperty("file.separator")) + 1);
MyFileEncryptor.encryptFile(srcpath,tarfile);
result.add(tarfile);
}
return result;
}
private static boolean uploadFile(FTPClient ftpClient, List<String> tarfileList) throws Exception {
boolean uploaded = true;
FileInputStream fis = null;
//连接FTP服务器
try {
for(String tarfile : tarfileList) {
fis = new FileInputStream(tarfile);
ftpClient.storeFile(tarfile.substring(tarfile.lastIndexOf(System.getProperty("file.separator"))+1), fis);
fis.close();
}
} catch (IOException e) {
logger.error("上传文件异常", e);
throw new CommonException(ErrorCode.FTP_CONNETION_ERROR);
} finally {
if (fis != null)
fis.close();
closeCon(ftpClient);
}
return uploaded;
}
public static void closeCon(FTPClient ftpClient) {
if (ftpClient != null) {
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static FTPClient connectServer(String ip, String port, String user, String pwd) throws CommonException {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ip, Integer.parseInt(port));
if (!ftpClient.login(user, pwd)) {
throw new CommonException(ErrorCode.FTP_CONNETION_ERROR);
}
} catch (IOException e) {
logger.error("连接FTP服务器异常", e);
throw new CommonException(ErrorCode.FTP_CONNETION_ERROR);
}
return ftpClient;
}
public static boolean removeDirectory(String remotePath, String fileName) throws CommonException, IOException {
logger.info("开始连接ftp服务器");
FTPClient ftpClient = connectServer(
PropertiesUtil.getProperty("ftp.id"),
PropertiesUtil.getProperty("ftp.port"),
PropertiesUtil.getProperty("ftp.user"),
PropertiesUtil.getProperty("ftp.password"));
changeWork(ftpClient, remotePath);
ftpClient.deleteFile(fileName);
logger.info("开始连接ftp服务器,结束上传,上传结果:{}");
return true;
}
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
private static void createDir(List<FtpFileParams> list) throws FileNotFoundException {
String path = ResourcePathUtil.getResourceRootPath() + "/temp/";
File create = new File(path);
if(!create.exists()){
create.mkdirs();
}
File dir = new File(list.get(0).getLocalPath());
if (!dir.exists()) {
dir.mkdirs();
}
}
}
2.FileUploadUtil.java
package com.esinhai.common.utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.*;
public class FileUploadUtil {
public static Map<String,String> getUrl(String originalName,String remotePath){
Map<String,String> map = new HashMap<>();
String date = UUIDUtil.uuid();
StringBuilder sb = new StringBuilder();
sb.append(ResourcePathUtil.getUploadPath(remotePath))
.append(date)
.append(originalName.substring(originalName.lastIndexOf(".")));
map.put("path",sb.toString());
map.put("date",date);
return map;
}
public static List<File> upload(Map<String,MultipartFile> map) throws Exception {
List<File> list = new ArrayList<>();
for(Map.Entry<String,MultipartFile> entry : map.entrySet()){
MultipartFile mf = entry.getValue();
String originalName = mf.getOriginalFilename();
String fileExtensionName = originalName.substring(originalName.lastIndexOf("."));
String fileName = entry.getKey() + fileExtensionName;
String value = ResourcePathUtil.getResourceRootPath("/static/log/");
File file = new File(value + fileName);
mf.transferTo(file);
list.add(file);
}
return list;
}
public static boolean upload(MultipartFile mf) throws Exception {
String originalName = mf.getOriginalFilename();
String value = ResourcePathUtil.getResourceRootPath("/static/");
File file = new File(value + originalName);
mf.transferTo(file);
return true;
}
public static void delete(List<String> filePaths){
for(String filePath : filePaths){
File file = new File(filePath);
file.delete();
}
}
}
3.ResourcePathUtil.java
package com.esinhai.common.utils;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
public class ResourcePathUtil {
public static String getResourceFile(String resourceName) throws FileNotFoundException {
return ResourceUtils.getURL("classpath:" + resourceName).getPath();
}
public static String getXmlRsaFile() throws FileNotFoundException {
return ResourceUtils.getURL("classpath:RSAKey.xml").getPath();
}
public static String getResourceRootPath() throws FileNotFoundException{
StringBuilder sb = new StringBuilder(ResourceUtils.getURL("classpath:application.yml").getPath());
String path = sb.substring(0,sb.lastIndexOf("/"));
path = path.substring(0,path.lastIndexOf("/"));
path = path.substring(0,path.lastIndexOf("/"));
return path;
}
public static String getResourceRootPath(String dirName) throws FileNotFoundException {
StringBuilder path = new StringBuilder(getResourceRootPath());
path.append(dirName);
File file = new File(path.toString());
if(!file.exists()){
file.mkdirs();
}
return path.toString();
}
public static String getUploadPath(String remotePath) {
return remotePath + "/" + DateUtils.getDate("yyyyMMdd") + "/";
}
}