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

来,任何的方法不懂的,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. 【20160815】noip模拟(未完)

    #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #inc ...

  2. 【Python实例二】之前期准备:Windows下的BeautifulSoup安装

    前言 一直久闻Python的爬虫很高效,而且操作便捷,因此决定开始练习爬虫的相关内容. 首先尝试的是Python的爬虫利器之一:BeautifulSoup.(这名字听起来就有种想要去探究的兴趣.... ...

  3. 【跑马灯】纯css3跑马灯demo

    我们写跑马灯一般都是用js控制定时器不断循环产生,但是定时器消耗比较大,特别是程序中很多用到定时器的时候,感觉有的时候比较卡.但是css3样式一般不会.这里主要的思路就是用css3代替js定时器实现一 ...

  4. 手把手教你配置苹果APNS推送服务|钿畑的博客 | 钿畑的博客

    http://www.360doc.com/content/15/0118/17/1073512_441822850.shtml# 钿畑的文章索引 1. 什么是推送通知 2. 什么是APNS? 3. ...

  5. JVM指令的使用深入详解

    原文地址:https://www.jb51.net/article/155293.htm 一.未归类系列A 此系列暂未归类. 指令码    助记符                            ...

  6. You have not concluded your merge. (MERGE_HEAD exists)(转)

    Git本地有修改如何强制更新 本地有修改和提交,如何强制用远程的库更新更新.我尝试过用git pull -f,总是提示 You have not concluded your merge. (MERG ...

  7. 【反演复习计划】【COGS2433】&&【bzoj3930,CQOI2015选数】爱蜜莉雅的冰魔法

    同bzoj3930. (日常盗题图) #include<bits/stdc++.h> #define N 1000010 #define yql 1000000007 #define ll ...

  8. 微信网页版的onclick事件不起作用

    我的错误是在跳转的url中拼接了url,如下: var myBaseUrl="https://xxx/"; function do() { $.ajax({ url :myBase ...

  9. 《JavaScript模式》精要

    P25. 如何避免eval()定义全局变量? 如: var jsstring = "var un = 1;"; eval(jsstring); console.log(typeof ...

  10. html实现点击章节自动调到开头

    #转载请联系 原理是用id的值结合a链接实现锚点效果.比较简单,直接放一段代码好了. <!DOCTYPE html> <html lang="en"> &l ...