【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码

时间:2024-10-20 00:06:02

和上一份简单 上传下载一样

来,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html

API拿走不谢!!!

1.FTP配置实体

 package com.agen.util;

 public class FtpConfig {
//主机ip
private String FtpHost = "192.168.18.252";
//端口号
private int FtpPort = 21;
//ftp用户名
private String FtpUser = "ftp";
//ftp密码
private String FtpPassword = "agenbiology";
//ftp中的目录 这里先指定的根目录
private String FtpPath = "/"; public String getFtpHost() {
return FtpHost;
}
public void setFtpHost(String ftpHost) {
FtpHost = ftpHost;
}
public int getFtpPort() {
return FtpPort;
}
public void setFtpPort(int ftpPort) {
FtpPort = ftpPort;
}
public String getFtpUser() {
return FtpUser;
}
public void setFtpUser(String ftpUser) {
FtpUser = ftpUser;
}
public String getFtpPassword() {
return FtpPassword;
}
public void setFtpPassword(String ftpPassword) {
FtpPassword = ftpPassword;
}
public String getFtpPath() {
return FtpPath;
}
public void setFtpPath(String ftpPath) {
FtpPath = ftpPath;
} }

2.FTP工具类,仅有一个删除文件夹【目录】的操作方法,删除文件夹包括文件夹下所有的文件

 package com.agen.util;

 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder; import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile; public class FtpUtils { /**
* 获取FTP连接
* @return
*/
public FTPClient getFTPClient() {
FtpConfig config = new FtpConfig();
FTPClient ftpClient = new FTPClient();
boolean result = true;
try {
//连接FTP服务器
ftpClient.connect(config.getFtpHost(), config.getFtpPort());
//如果连接
if (ftpClient.isConnected()) {
//提供用户名/密码登录FTP服务器
boolean flag = ftpClient.login(config.getFtpUser(), config.getFtpPassword());
//如果登录成功
if (flag) {
//设置编码类型为UTF-8
ftpClient.setControlEncoding("UTF-8");
//设置文件类型为二进制文件类型
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} else {
result = false;
}
} else {
result = false;
}
//成功连接并 登陆成功 返回连接
if (result) {
return ftpClient;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 删除文件夹下所有文件
* @return
* @throws IOException
*/
public boolean deleteFiles(String pathname) throws IOException{
FTPClient ftpClient = getFTPClient();
ftpClient.enterLocalPassiveMode();//在调用listFiles()方法之前需要调用此方法
FTPFile[] ftpFiles = ftpClient.listFiles(new String((pathname).getBytes("UTF-8"),"iso-8859-1"));
System.out.println(ftpFiles == null ? null :ftpFiles.length );
if(ftpFiles.length > 0){
for (int i = 0; i < ftpFiles.length; i++) {
System.out.println(ftpFiles[i].getName());
if(ftpFiles[i].isDirectory()){
deleteFiles(pathname+"/"+ftpFiles[i].getName());
}else{
System.out.println(pathname);
//这里需要提供删除文件的路径名 才能删除文件
ftpClient.deleteFile(new String((pathname+"/"+ftpFiles[i].getName()).getBytes("UTF-8"),"iso-8859-1"));
FTPFile [] ftFiles = ftpClient.listFiles(new String((pathname).getBytes("UTF-8"),"iso-8859-1"));
if(ftFiles.length == 0){//如果文件夹中现在已经为空了
ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"),"iso-8859-1"));
}
}
}
}
return true;
} /**
* 关闭 输入流或输出流
* @param in
* @param out
* @param ftpClient
*/
public void close(InputStream in, OutputStream out,FTPClient ftpClient) {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("输入流关闭失败");
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("输出流关闭失败");
}
}
if (null != ftpClient) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Ftp服务关闭失败!");
}
}
} }

删除方法中,调用listFiles()方法之前,需要调用ftpClient.enterLocalPassiveMode();

关于调用listFiles()方法,有以下几种情况需要注意:

①listFiles()方法可能返回为null,这个问题我也遇到了,这种原因是因为FTP服务器的语言环境,编码方式,时间戳等各种的没有处理好或者与程序端并不一致

②首先可以使用listNames()方法排除是否是路径的原因,路径编码方式等原因

③其次,调整好路径后,有如下提示的错误Caused by: java.lang.ClassNotFoundException: org.apache.oro.text.regex.MalformedPatternException,需要导入一个架包 【jakarta-oro-2.0.8.jar】

【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码

3.实际用到的FTP上传【创建多层中文目录】+下载【浏览器下载OR服务器下载】+删除       【处理FTP编码方式与本地编码不一致】

     /**
* 上传至FTP服务器
* @param partFile
* @param request
* @param diseaseName
* @param productName
* @param diseaseId
* @return
* @throws IOException
*/
@RequestMapping("/uploadFiles")
@ResponseBody
public boolean uploadFiles(@RequestParam("upfile")MultipartFile partFile,HttpServletRequest request,String diseaseName,String productName,String diseaseId) throws IOException{
Disease disease = new Disease();
disease.setDiseaseId(diseaseId);
Criteria criteria = getCurrentSession().createCriteria(Filelist.class);
criteria.add(Restrictions.eq("disease", disease));
Filelist flFilelist = filelistService.uniqueResult(criteria);
if(flFilelist == null){
FtpUtils ftpUtils = new FtpUtils();
boolean result = true;
InputStream in = null;
FTPClient ftpClient = ftpUtils.getFTPClient();
if (null == ftpClient) {
System.out.println("FTP服务器未连接成功!!!");
return false;
}
try { String path = "/file-ave/";
ftpClient.changeWorkingDirectory(path);
System.out.println(ftpClient.printWorkingDirectory());
//创建产品文件夹 转码 防止在FTP服务器上创建时乱码
ftpClient.makeDirectory(new String(productName.getBytes("UTF-8"),"iso-8859-1"));
//指定当前的工作路径到产品文件夹下
ftpClient.changeWorkingDirectory(path+new String(productName.getBytes("UTF-8"),"iso-8859-1"));
//创建疾病文件夹 转码
ftpClient.makeDirectory(new String(diseaseName.getBytes("UTF-8"),"iso-8859-1"));
//指定当前的工作路径到疾病文件夹下
ftpClient.changeWorkingDirectory(path+new String(productName.getBytes("UTF-8"),"iso-8859-1")+"/"+new String(diseaseName.getBytes("UTF-8"),"iso-8859-1")); // 得到上传的文件的文件名
String filename = partFile.getOriginalFilename();
in = partFile.getInputStream();
ftpClient.storeFile(new String(filename.getBytes("UTF-8"),"iso-8859-1"), in);
path += productName+"/"+diseaseName+"/"; DecimalFormat df = new DecimalFormat();
String fileSize = partFile.getSize()/1024>100 ? (partFile.getSize()/1024/1024>100? df.format((double)partFile.getSize()/1024/1024/1024)+"GB" :df.format((double)partFile.getSize()/1024/1024)+"MB" ) :df.format((double)partFile.getSize()/1024)+"KB";
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user"); Filelist filelist = new Filelist();
filelist.setFileId(UUID.randomUUID().toString());
filelist.setFileName(filename);
filelist.setFilePath(path+filename);
filelist.setFileCre(fileSize);
filelist.setCreateDate(new Timestamp(System.currentTimeMillis()));
filelist.setUpdateDate(new Timestamp(System.currentTimeMillis()));
filelist.setTransPerson(user.getUserId());
filelist.setDisease(disease);
filelistService.save(filelist); return result; } catch (IOException e) {
e.printStackTrace();
return false;
} finally {
ftpUtils.close(in, null, ftpClient);
}
}else{
return false;
}
} /**
* 删除文件
* @param filelistId
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
@RequestMapping("/filelistDelete")
@ResponseBody
public boolean filelistDelete(String []filelistId) throws UnsupportedEncodingException, IOException{
for (String string : filelistId) {
Filelist filelist = filelistService.uniqueResult("fileId", string);
String filePath = filelist.getFilePath();
FtpUtils ftpUtils = new FtpUtils();
FTPClient ftpClient = ftpUtils.getFTPClient();
InputStream inputStream = ftpClient.retrieveFileStream(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
if(inputStream != null || ftpClient.getReplyCode() == 550){
ftpClient.deleteFile(filePath);
}
filelistService.deleteById(string);
}
return true;
} /**
* 下载到本地
* @param fileId
* @param response
* @return
* @throws IOException
* @throws InterruptedException
*/
@RequestMapping("/fileDownload")
public String fileDownload(String fileId,HttpServletResponse response) throws IOException, InterruptedException{
Filelist filelist = filelistService.get(fileId);
Assert.notNull(filelist);
String filePath = filelist.getFilePath();
String fileName = filelist.getFileName();
String targetPath = "D:/biologyInfo/Download/";
File file = new File(targetPath);
while(!file.exists()){
file.mkdirs();
}
FtpUtils ftpUtils = new FtpUtils();
FileOutputStream out = null;
FTPClient ftpClient = ftpUtils.getFTPClient();
if (null == ftpClient) {
System.out.println("FTP服务器未连接成功!!!");
}
try {
//下载到 应用服务器而不是本地
// //要写到本地的位置
// File file2 = new File(targetPath + fileName);
// out = new FileOutputStream(file2);
// //截取文件的存储位置 不包括文件本身
// filePath = filePath.substring(0, filePath.lastIndexOf("/"));
// //文件存储在FTP的位置
// ftpClient.changeWorkingDirectory(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
// System.out.println(ftpClient.printWorkingDirectory());
// //下载文件
// ftpClient.retrieveFile(new String(fileName.getBytes("UTF-8"),"iso-8859-1"), out);
// return true; //下载到 客户端 浏览器
InputStream inputStream = ftpClient.retrieveFileStream(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
OutputStream outputStream = response.getOutputStream();
byte[] b = new byte[1024];
int length = 0;
while ((length = inputStream.read(b)) != -1) {
outputStream.write(b, 0, length);
} } catch (IOException e) {
e.printStackTrace();
} finally {
ftpUtils.close(null, out, ftpClient);
}
return null;
}

最后注意一点:

FTP服务器不一样,会引发很多的问题,因为FTP服务器的语言环境,编码方式,时间戳等各种的原因,导致程序中需要进行大量的类似的处理,要跟FTP进行匹配使用。

因为FTP架包是apache的,所以使用apache自己的FTP服务器,是匹配度最高的,传入文件路径等都不需要考虑转码等各种各样的问题!!!

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------附录------------------------------------------------------------------------------------

FTPFile[] ftpFiles = ftpClient.listFiles(new String((pathname).getBytes("UTF-8"),"iso-8859-1"));

方法的调用,报错如下:

 java.lang.NoClassDefFoundError: org/apache/oro/text/regex/MalformedPatternException
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createUnixFTPEntryParser(DefaultFTPFileEntryParserFactory.java:169)
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:94)
at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:2358)
at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2141)
at com.sxd.ftp.FtpUtils.deleteFiles(FtpUtils.java:170)
at com.sxd.ftp.FtpUtils.test(FtpUtils.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.apache.oro.text.regex.MalformedPatternException
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 29 more

解决方法:
jakarta-oro-2.0.8.jar