FTP的上传下载及相关的使用

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();
        }
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容