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

来,任何的方法不懂的,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】

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

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

  1. vb.net FTP上传下载,目录操作

    https://blog.csdn.net/dzweather/article/details/51429107 FtpWebRequest与FtpWebResponse类用来与特定FTP服务器进行沟 ...

  2. ftp org.apache.commons.net.ftp.FTPClient 判断文件是否存在

    String path = "/SJPT/ONPUT/HMD_TEST/" ; FtpTool.getFTPClient().changeWorkingDirectory(path ...

  3. org.apache.commons.net.ftp

    org.apache.commons.NET.ftp Class FTPClient类FTPClient java.lang.Object Java.lang.Object继承 org.apache. ...

  4. 【FTP】使用org.apache.commons.net.ftp.FTPClient 实现FTP的上传下载

    在此之前,在项目中加上FTP的架包 第一步:配置FTP服务器的相关配置 FtpConfig.java  实体类(配置类) package com.sxd.ftp; public class FtpCo ...

  5. Java 利用Apache Commons Net 实现 FTP文件上传下载

    package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...

  6. org.apache.commons.net.ftp.FTPConnectionClosedException: Connection closed without indication

    Ftp问题 最近遇到了ftp读取中文乱码的问题,代码中使用的是FtpClient.google一下找到了解决方案. FTP协议里面,规定文件名编码为iso-8859-1,FTP类中默认的编码也是这个. ...

  7. ftp上传下载 java FTPClient (zhuan)

    项目需要,网上搜了搜,很多,但问题也不少,估计转来转去,少了不少东西,而且也情况也不太一样.没办法,只能自己去写一个. 一,    安装sserv-u ftp服务器 版本10.1.0.1 我所设服务器 ...

  8. Java使用Apache Commons Net的FtpClient进行下载时会宕掉的一种优化方法

    在使用FtpClient进行下载测试的时候,会发现一个问题,就是我如果一直重复下载一批文件,那么经常会宕掉. 也就是说程序一直停在那里一动不动了. 每个人的情况都不一样,我的情况是因为我在本地之前就有 ...

  9. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

随机推荐

  1. 【BZOJ 3907】网格(Catalan数)

    题目链接 这个题推导公式跟\(Catalan\)数是一样的,可得解为\(C_{n+m}^n-C_{n+m}^{n+1}\) 然后套组合数公式\(C_n^m=\frac{n!}{m!(n-m)!}\) ...

  2. 玩转Metasploit系列(第二集)

    在上一节的内容中,大家了解了Metasploit的结构.这一节我们主要介绍的是msfconsole的理论. msfconsole理论 在MSF里面msfconsole可以说是最流行的一个接口程序.很多 ...

  3. 2017年上海金马五校程序设计竞赛:Problem G : One for You (博弈)

    Description Given a m × n chessboard, a stone is put on the top-left corner (1, 1). Kevin and Bob ta ...

  4. HDU3746(KMP求循环节)

    Cyclic Nacklace Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  5. VC++/MFC中调用CHM帮助文档的方法

    转载:http://blog.csdn.net/hediping9811/article/details/23341387 (1)用Word编辑好帮助文档,并保存为网页格式,如mhtml格式. (2) ...

  6. Linux kernel中断子系统之(五):驱动申请中断API【转】

    转自:http://www.wowotech.net/linux_kenrel/request_threaded_irq.html 一.前言 本文主要的议题是作为一个普通的驱动工程师,在撰写自己负责的 ...

  7. Github上的几个C++开源项目

    Github上的几个C++开源项目 http://blog.csdn.net/fyifei0558/article/details/47001677 http://www.zhihu.com/ques ...

  8. 使用pandas进行数据清洗

    本文转载自:蓝鲸的网站分析笔记 原文链接:使用python进行数据清洗 目录: 数据表中的重复值 duplicated() drop_duplicated() 数据表中的空值/缺失值 isnull() ...

  9. 安装VMware Tools的步骤和那些坑

    背景环境:VMware workstation 12.5+Ubuntu16.04 首先VMware Tools在ubuntu中是及其不稳定的,也就是说,当你点击菜单栏中的install vmware ...

  10. linux awk学习笔记

    awk学习笔记 awk语法格式 awk '{pattern + action}' {filenames} awk作用 awk的最基本功能是在文件或者字符串中基于指定规则浏览和抽取信息,awk抽取信息后 ...