一、导入FTP依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
二、工具类
/**
* 实现连接FTP服务器,实现文件的上传和下载
*/
public class FtpUtils {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
private static Calendar calendar = Calendar.getInstance();
/**
* 获取FTPClient对象
*
* @param ftpHost
* FTP主机服务器
* @param ftpPassword
* FTP 登录密码
* @param ftpUserName
* FTP登录用户名
* @param ftpPort
* FTP端口 默认为21
* @return
*/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
FTPClient ftpClient = null;
try {
//创建一个ftp客户端
ftpClient = new FTPClient();
//解决FTP获取文件名中文字符乱码的问题
ftpClient.setControlEncoding("UTF-8");
// 连接FTP服务器
ftpClient.connect(ftpHost, ftpPort);
// 登陆FTP服务器
ftpClient.login(ftpUserName, ftpPassword);
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
} else {
System.out.println("FTP连接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
/**
* 下载文件到本地服务器
* @param ftpPath 要下载的ftp文件所在的父文件夹路径
* @param localPath 本地存储该文件的父文件夹路径
* @param fileName 文件名称
*/
public static Map<String,Object> downloadFile(FTPClient ftpClient, String ftpPath, String localPath, String fileName) {
Map<String, Object> map = new HashMap<>();
try {
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
File localFile = new File(localPath + File.separatorChar + fileName);
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(fileName, os);
os.close();
ftpClient.logout();
map.put("status",true);
} catch (FileNotFoundException e) {
map.put("status",false);
map.put("message","没有找到" + ftpPath + "文件");
e.printStackTrace();
} catch (SocketException e) {
map.put("status",false);
map.put("message","连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
map.put("status",false);
map.put("message","文件读取错误。");
e.printStackTrace();
}
return map;
}
/**
* 下载文件到客户端
* @param ftpPath 要下载的ftp文件所在的父文件夹路径
* @param fileName 文件名称
*/
public static Map<String,Object> downloadFile1(FTPClient ftpClient, String ftpPath, HttpServletResponse response,String fileName) {
Map<String, Object> map = new HashMap<>();
try {
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
response.setContentType("multipart/form-data");
//URLEncoder.encode(file.getName(),"UTF-8") 解决中文文件名称;replace("+", "%20")解决空格问题
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8").replace("+", "%20"));
ServletOutputStream os = response.getOutputStream();
ftpClient.retrieveFile(fileName, os);
os.close();
ftpClient.logout();
map.put("status",true);
System.out.println("下载成功!");
} catch (FileNotFoundException e) {
map.put("status",false);
map.put("message","没有找到" + ftpPath + "文件");
e.printStackTrace();
} catch (SocketException e) {
map.put("status",false);
map.put("message","连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
map.put("status",false);
map.put("message","文件读取错误。");
e.printStackTrace();
}
return map;
}
/**
* 上传文件
*
* @param ftpPath ftp文件存放物理路径
* @param fileName 文件路径
* @param input 文件输入流,即从本地服务器读取文件的IO输入流
*/
public static Map<String,Object> uploadFile(FTPClient ftpClient, String ftpPath, String fileName,InputStream input){
Map<String, Object> map = new HashMap<>();
try {
ftpClient.makeDirectory(ftpPath);//防止因上传目录不存在导致文件上传失败的情况
ftpClient.changeWorkingDirectory(ftpPath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//解决文件名中包含中文时文件无法上传的问题
fileName=new String(fileName.getBytes("GBK"),"iso-8859-1");
ftpClient.setBufferSize(1024 * 1024 * 10);//将缓冲区改为10M,提升文件上传速率
boolean upload_status = ftpClient.storeFile(fileName, input);
//关流(必须)
input.close();
ftpClient.logout();
if (upload_status) {
map.put("status",true);
map.put("message","文件上传成功!");
} else {
map.put("status",false);
map.put("message","该FTP账户文件读写权限不足,文件上传失败!");
}
} catch (Exception e) {
map.put("status",false);
map.put("message","文件上传失败!");
return map;
}
return map;
}
/**
* 分页获取FTP中指定路径下的文件
* @param ftpClient
* @param folderPath
* @throws IOException
*/
public static Map<String,Object> getFiles(FTPClient ftpClient, String folderPath, int pageNum, int pageSize) {
Map<String, Object> returnMap = new HashMap<>();
List<Object> fileList = new ArrayList<>();
FTPFile[] ftpFiles = new FTPFile[0];
try {
ftpFiles = ftpClient.listFiles(folderPath);
returnMap.put("total",ftpFiles.length);
for(int i=0; i < ftpFiles.length; i++) {
Map<String, Object> map = new HashMap<>();
map.put("name",ftpFiles[i].getName());
long size = ftpFiles[i].getSize();
String s = size/1024 + "kb";
map.put("size",s);
String modificationTime = ftpClient.getModificationTime(folderPath + "/" + ftpFiles[i].getName());
modificationTime = modificationTime.substring(modificationTime.indexOf(" ")+1);
Date parse = sdf1.parse(modificationTime);
calendar.setTime(parse);
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date time = calendar.getTime();
modificationTime = sdf.format(time);
map.put("date",modificationTime);
fileList.add(map);
}
returnMap.put("rows",fileList);
ftpClient.logout();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return returnMap;
}
/**
* 获取FTP中指定路径下的所有文件夹
* @param ftpClient
* @param path
* @throws IOException
*/
public static List<Object> getDirectories(FTPClient ftpClient, String path) {
List<Object> directoryList = new ArrayList<>();
FTPFile[] listDirectories = new FTPFile[0];
try {
listDirectories = ftpClient.listDirectories(path);
for (int i = 0; i< listDirectories.length; i++) {
Map<String, Object> map = new HashMap<>();
map.put("name",listDirectories[i].getName());
directoryList.add(map);
}
ftpClient.logout();
} catch (IOException e) {
throw new RuntimeException(e);
}
return directoryList;
}
public static List<Map<String, Object>> getAllFiles(FTPClient ftpClient){
List<Map<String, Object>> list = new ArrayList<>();
try {
// 获取根目录下的所有文件和文件夹
FTPFile[] files = ftpClient.listFiles("/");
for (FTPFile file : files) {
int parentId = 0;
Map<String, Object> map = new HashMap<>();
List<Map<String, Object>> childlist = new ArrayList<>();
// 如果是文件夹,递归列出子文件夹中的文件
map.put("name",file.getName());
map.put("parentId",parentId);
map.put("id",UUID.randomUUID());
if (file.isDirectory()) {
childlist = listFilesInDirectory(ftpClient, "/" + file.getName(),parentId + 1);
map.put("children",childlist);
}else {
map.put("size",file.getSize()/1024 + "kb");
String modificationTime = ftpClient.getModificationTime("/" + file.getName());
modificationTime = modificationTime.substring(modificationTime.indexOf(" ")+1);
Date parse = sdf1.parse(modificationTime);
calendar.setTime(parse);
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date time = calendar.getTime();
modificationTime = sdf.format(time);
map.put("date",modificationTime);
}
list.add(map);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return list;
}
private static List<Map<String, Object>> listFilesInDirectory(FTPClient ftpClient, String dirPath,int parentId) {
List<Map<String, Object>> list = new ArrayList<>();
try {
FTPFile[] subFiles = ftpClient.listFiles(dirPath);
for (FTPFile file : subFiles) {
Map<String, Object> map = new HashMap<>();
List<Map<String, Object>> childlist = new ArrayList<>();
map.put("name",file.getName());
map.put("parentId",parentId);
map.put("id",UUID.randomUUID());
// 如果是文件夹,递归列出子文件夹中的文件
if (file.isDirectory()) {
childlist = listFilesInDirectory(ftpClient, dirPath + "/" + file.getName(),parentId + 1);
map.put("children",childlist);
}else{
map.put("size",file.getSize()/1024 + "kb");
String modificationTime = ftpClient.getModificationTime(dirPath + "/" + file.getName());
modificationTime = modificationTime.substring(modificationTime.indexOf(" ")+1);
Date parse = sdf1.parse(modificationTime);
calendar.setTime(parse);
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date time = calendar.getTime();
modificationTime = sdf.format(time);
map.put("date",modificationTime);
// System.out.println(modificationTime);
}
list.add(map);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return list;
}
/**
* 删除指定文件
* @param ftpClient
* @param pathName
*/
public static Boolean deleteFile(FTPClient ftpClient,String pathName){
Boolean flag = null;
try {
// 获取指定路径下的文件列表
FTPFile[] files = ftpClient.listFiles(pathName);
// 检查文件是否存在
if (files.length > 0) {
ftpClient.deleteFile(pathName);
flag = true;
} else {
flag = false;
}
ftpClient.logout();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return flag;
}
/**
* 关闭FTP服务链接
* @throws IOException
*/
public static void disConnection(FTPClient ftpClient) {
try {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
System.out.println("连接关闭!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}