package com.pfframe.service.filecenter.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;
import com.pfframe.service.filecenter.IFileCenterService;
public class FileCenterFTPServiceImpl implements IFileCenterService{
private ThreadLocal<FTPClient> ftpClientThreadLocal = new ThreadLocal<FTPClient>();
private FileInputStream fis = null;
private Boolean isSuccess ;
private String url;
private String loginName;
private String password;
public void setUrl(String url) {
this.url = url;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public void setPassword(String password) {
this.password = password;
}
/***
*
* @function 获取FTPClient对象
* @return FTPClient
* @throws Exception
*/
private FTPClient achieveFTPClient() throws IOException{
if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {
return ftpClientThreadLocal.get();
} else {
FTPClient ftpClient = new FTPClient(); //构造一个FtpClient实例
// ftpClient.setControlEncoding(encoding); //设置字符集
connect(ftpClient); //连接到ftp服务器
//设置为passive模式
// if (passiveMode) {
// ftpClient.enterLocalPassiveMode();
// }
// setFileType(ftpClient); //设置文件传输类型
// try {
// ftpClient.setSoTimeout(clientTimeout);
// } catch (SocketException e) {
// throw new FTPClientException("Set timeout error.", e);
// }
ftpClientThreadLocal.set(ftpClient);
return ftpClient;
}
}
/***
*
* @function ftp连接
* @param ftpClient
* @return Boolean
* @throws Exception
*/
private boolean connect(FTPClient ftpClient) throws IOException{
try {
ftpClient.connect(url);
// 连接后检测返回码来校验连接是否成功
int reply = ftpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
//登陆到ftp服务器
if (ftpClient.login(loginName, password)) {
// setFileType(ftpClient);
return true;
}
} else {
ftpClient.disconnect();
throw new IOException("FTP server refused connection.");
}
} catch (IOException e) {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect(); //断开连接
} catch (IOException e1) {
throw new IOException("Could not disconnect from server.", e1);
}
}
throw new IOException("Could not connect to server.", e);
}
return false;
}
/***
* @function 断开连接
*
* @throws IOException
*/
public void disconnect() throws IOException {
try {
FTPClient ftpClient = achieveFTPClient();
if (ftpClient.isConnected()) {
ftpClient.disconnect();
ftpClient = null;
}
} catch (IOException e) {
throw new IOException("Could not disconnect from server.", e);
}
}
@Override
public Boolean fileUpload(String directory, Map<String,File> fileMap) throws Exception{
try {
isSuccess = false;
for (String key : fileMap.keySet()){
System.out.println("文件名="+key);
FTPClient ftpClient = achieveFTPClient();
fis = new FileInputStream(fileMap.get(key));
String[] dirArr = directory.split("/");
directory = "";
for(int i =0;i<dirArr.length;i++){
directory = directory +"/" +dirArr[i];
Boolean isExsit = false;
System.out.println(directory);
FTPFile[] dirs = ftpClient.listDirectories(directory);
for(int j =0;j<dirs.length;j++){
if(dirs[j].getName().equals(dirArr[i]));
isExsit = true;
}
if(!isExsit){
ftpClient.makeDirectory(directory);
}
}
// System.out.println(new String(directory.getBytes("GBK"),"ISO-8859-1"));
ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"));
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//@edit hjj @date 2015/08/07 @desc上传中文名字
isSuccess = ftpClient.storeFile(new String(key.getBytes("GBK"),"iso-8859-1"), fis);
System.out.println(isSuccess);
fis.close();
}
return isSuccess;
} catch (Exception er) {
throw new Exception("上传文件失败 : " + er);
} finally {
disconnect();
}
}
@Override
public Boolean inputStreamUpload(String directory,String fileName, InputStream inputStream) throws Exception {
try {
isSuccess = false;
// System.out.println("文件名="+fileName);
FTPClient ftpClient = achieveFTPClient();
String[] dirArr = directory.split("/");
directory = dirArr[0];
for(int i =1;i<dirArr.length;i++){
directory = directory +"/" +dirArr[i];
Boolean isExsit = false;
FTPFile[] dirs = ftpClient.listDirectories(directory);
for(int j =0;j<dirs.length;j++){
if(dirs[j].getName().equals(dirArr[i]));
isExsit = true;
}
if(!isExsit){
ftpClient.makeDirectory(directory);
}
}
ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"));
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//@edit hjj @date 2015/08/07 @desc上传中文名字
isSuccess = ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), inputStream);
System.out.println(isSuccess);
return isSuccess;
} catch (Exception er) {
throw new Exception("上传文件失败 : " + er);
} finally {
disconnect();
}
}
@Override
public Boolean delFile(List<String> pathNames) throws IOException {
try {
isSuccess = false;
FTPClient ftpClient = achieveFTPClient();
for(int i =0;i<pathNames.size();i++){
System.out.println(pathNames.get(i));
isSuccess = ftpClient.deleteFile(new String(pathNames.get(i).getBytes("GBK"),"ISO-8859-1"));
}
return isSuccess;
} catch (IOException er) {
throw new IOException("删除文件失败 : " + er);
} finally {
disconnect();
}
}
@Override
public InputStream fileInputStreamDownload(String remoteName) throws IOException {
InputStream is = null;
try {
FTPClient ftpClient = achieveFTPClient();
is = ftpClient.retrieveFileStream(new String(remoteName.getBytes("GBK"),"ISO-8859-1"));
} catch (IOException er) {
throw new IOException("下载文件流失败 : " + er.getMessage());
}
return is;
}
@Override
public Boolean fileDownload(String directory,String downloadpath, String localName) throws IOException {
try {
isSuccess = false;
FTPClient ftpClient = achieveFTPClient();
ftpClient.setControlEncoding("GBK");
ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"));
FTPFile[] fileArr = ftpClient.listFiles();
// System.out.println("directory="+directory);
// System.out.println(downloadpath);
// System.out.println(localName);
for(FTPFile file :fileArr){
String fileName = file.getName();
// System.out.println(fileName);
if(fileName.equalsIgnoreCase(localName)){
File localFile = new File(downloadpath+"/"+file.getName());
OutputStream os = new FileOutputStream(localFile);
isSuccess = ftpClient.retrieveFile(new String(fileName.getBytes("GBK"),"ISO-8859-1"), os);
os.flush();
os.close();
}
}
return isSuccess;
} catch (Exception er) {
throw new IOException("下载文件失败 : " + er.getMessage());
} finally {
disconnect();
}
}
@Override
public List<FTPFile> achieveFolderListByDir(String directory) throws IOException {
try {
FTPClient ftpClient = achieveFTPClient();
ftpClient.setControlEncoding("GBK");//设置编码,否则中文名是乱码
// System.out.println(directory);
// if(!ftpClient.changeWorkingDirectory(directory)){
// ftpClient.makeDirectory(directory);
// }
//解决中文路径的问题
if(ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"))) {
FTPFile[] ftpFileArr = ftpClient.listFiles();
// System.out.println(ftpFileArr.length);
List<FTPFile> folderList = new ArrayList<FTPFile>();
for(FTPFile file : ftpFileArr){
// System.out.println(file.getName());
folderList.add(file);
}
return folderList;
} else {
return null;
}
} catch (Exception er) {
throw new IOException("获取文件列表失败 : " + er.getMessage());
} finally {
disconnect();
}
}
@Override
public Boolean dirDownload(String directory, String downloadpath)
throws IOException {
try {
isSuccess = false;
FTPClient ftpClient = achieveFTPClient();
ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"));
FTPFile[] fileArr = ftpClient.listFiles();
System.out.println("directory="+directory);
System.out.println(downloadpath);
for(FTPFile file :fileArr){
File localFile = new File(downloadpath+"/"+file.getName());
OutputStream os = new FileOutputStream(localFile);
isSuccess = ftpClient.retrieveFile(file.getName(), os);
os.flush();
os.close();
}
return isSuccess;
} catch (Exception er) {
throw new IOException("路径下载失败 : " + er.getMessage());
} finally {
disconnect();
}
}
public Boolean overwriteFile(String dir, String remoteName, InputStream local) throws IOException {
isSuccess = false;
FTPClient ftpClient = achieveFTPClient();
if( ftpClient.changeWorkingDirectory(dir) ) {
ftpClient.changeWorkingDirectory(dir);
FTPFile[] ftpFiles = ftpClient.listFiles(remoteName);
if( ftpFiles.length == 0 ) {
System.out.println("文件不存在!");
isSuccess = ftpClient.storeFile(remoteName, local);
} else {
System.out.println("文件存在!");
ftpClient.dele(remoteName);
ftpClient.setControlEncoding("utf-8");
isSuccess = ftpClient.appendFile(remoteName, local);
}
} else {
throw new IOException("文件路径不正确!");
}
disconnect();
return isSuccess;
}
@Override
public Boolean rename(String dir, String from, String to) throws IOException {
isSuccess = false;
FTPClient ftpClient = achieveFTPClient();
if( ftpClient.changeWorkingDirectory(dir) ) {
ftpClient.changeWorkingDirectory(dir);
isSuccess = ftpClient.rename(new String(from.getBytes("GBK"),"ISO-8859-1"), new String(to.getBytes("GBK"),"ISO-8859-1"));
} else {
throw new IOException("文件路径不正确!");
}
disconnect();
return isSuccess;
}
@Override
public Boolean makeDir(String dir) throws IOException {
isSuccess = false;
try {
FTPClient ftpClient = achieveFTPClient();
dir = new String(dir.getBytes("GBK"),"ISO-8859-1");
String[] dirArr = dir.split("/");
dir = "";
for(int i =0;i<dirArr.length;i++){
dir = dir +"/" +dirArr[i];
Boolean isExsit = false;
// System.out.println(dir);
FTPFile[] dirs = ftpClient.listDirectories(dir);
for(int j =0;j<dirs.length;j++){
if(dirs[j].getName().equals(dirArr[i]));
isExsit = true;
}
if(!isExsit){
isSuccess = ftpClient.makeDirectory(dir);
}
}
} catch (Exception er) {
System.out.println(er);
throw new IOException("创建文件夹失败");
}
disconnect();
return isSuccess;
}
@Override
public Boolean delDir(List<String> dirNames) throws IOException {
try {
return innerDelDir(dirNames);
} catch (IOException er) {
throw new IOException("删除文件夹失败 : " + er);
} finally {
disconnect();
}
}
/***
* 文件夹删除,递归方法
* @param dirNames
* @return
* @throws IOException
*/
private Boolean innerDelDir(List<String> dirNames) throws IOException {
isSuccess = false;
FTPClient ftpClient = achieveFTPClient();
for (int i = 0; i < dirNames.size(); i++) {
String dirName = dirNames.get(i);
// System.out.println("删除的文件夹地址:" + dirName);
FTPFile[] files = ftpClient.listFiles(new String(dirName
.getBytes("GBK"), "ISO-8859-1"));
for (FTPFile ftpFile : files) {
String fileName = ftpFile.getName();
fileName = new String(fileName
.getBytes("ISO-8859-1"), "GBK");
// System.out.println("fileName="+fileName);
if (ftpFile.isDirectory()) {
List<String> dirList = new ArrayList<String>();
dirList.add(dirName + "/" + fileName);
this.innerDelDir(dirList);
isSuccess = ftpClient.removeDirectory(fileName);
// if(isSuccess)
// System.out.println("删除文件夹:"+fileName+"成功!");
// else
// System.out.println("删除文件夹:"+fileName+"失败!");
}
if (ftpFile.isFile()) {
// System.out.println(dirName);
isSuccess = ftpClient.deleteFile(new String((dirName + "/" + fileName)
.getBytes("GBK"), "ISO-8859-1"));
// if(isSuccess)
// System.out.println("删除文件:"+fileName+"成功!");
// else
// System.out.println("删除文件:"+fileName+"失败!");
}
}
isSuccess = ftpClient.removeDirectory(new String(dirName
.getBytes("GBK"), "ISO-8859-1"));
}
return isSuccess;
}
@Override
public List<String> listNames(String dir) throws IOException {
List<String> nameList = null;
try {
FTPClient ftpClient = achieveFTPClient();
ftpClient.setControlEncoding("GBK");//设置编码,否则中文名是乱码
String[] nameArr = ftpClient.listNames(new String(dir
.getBytes("GBK"), "ISO-8859-1"));
nameList = new ArrayList<String>();
if(nameArr != null && nameArr.length > 0) {
for(int nI = 0;nI < nameArr.length;nI++) {
// System.out.println(nameArr[nI]);
nameList.add(nameArr[nI]);
}
}
} catch (Exception er) {
throw new IOException("获取文件名列表失败 : " + er);
} finally {
disconnect();
}
return nameList;
}
@Override
public Boolean fileDownload(String dir,String remoteName,OutputStream local)
throws IOException {
Boolean isSuccess = false;
try {
FTPClient ftpClient = achieveFTPClient();
ftpClient.changeWorkingDirectory(new String(dir.getBytes("GBK"),"ISO-8859-1"));
isSuccess = ftpClient.retrieveFile(new String(remoteName.getBytes("GBK"),"ISO-8859-1"), local);
} catch (Exception er) {
throw new IOException("下载文件入输出流失败 : " + er);
} finally {
disconnect();
}
return isSuccess;
}
@Override
public List<FTPFile> achieveFolderListByDir(String directory,
FTPFileFilter filter) throws IOException {
try {
FTPClient ftpClient = achieveFTPClient();
ftpClient.setControlEncoding("GBK");//设置编码,否则中文名是乱码
FTPFile[] ftpFileArr = ftpClient.listFiles(new String(directory.getBytes("GBK"),"ISO-8859-1"),filter);
// System.out.println(ftpFileArr.length);
List<FTPFile> folderList = new ArrayList<FTPFile>();
for(FTPFile file : ftpFileArr){
// System.out.println(file.getName());
folderList.add(file);
}
return folderList;
} catch (Exception er) {
throw new IOException("获取文件列表失败 : " + er.getMessage());
} finally {
disconnect();
}
}
}
FTP的上传下载及相关的使用
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- FTP文件上传及回执文件下载并解析 功能简介: 操作流程: 使用说明双击文件夹下的exe的执行文件,程序就自动运行...