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 ftpClientThreadLocal = new ThreadLocal();
    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 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 pathNames) throws IOException {
        try {
            isSuccess = false;
            FTPClient ftpClient = achieveFTPClient();
            for(int i =0;i 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 folderList = new ArrayList();
                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 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 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 dirList = new ArrayList();
                    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 listNames(String dir) throws IOException {
        List nameList = null;
        try {
            FTPClient ftpClient = achieveFTPClient();
            ftpClient.setControlEncoding("GBK");//设置编码,否则中文名是乱码
            String[] nameArr = ftpClient.listNames(new String(dir
                    .getBytes("GBK"), "ISO-8859-1"));
            nameList = new ArrayList();
            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 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 folderList = new ArrayList();
            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的上传下载及相关的使用)