實現 ftp 文件/文件夾的上傳下載以及刪除

基於apache commons-net的ftp 文件上傳下載及刪除 工具類,分享出來希望有人用得着,也方便自己以後查看~~~

package com.sslinm.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**
 * 
 *【功能描述:ftp 工具類】
 *【功能詳細描述:逐條詳細描述功能】 
 * @author  【lfssay】
 * @see     【相關類/方法】
 * @version 【類版本號, 2013-8-19 下午4:39:37】
 * @since   【產品/模塊版本】
 */

public class FtpUtils {

   
    public static void main(String[] args) {
//        boolean flag = fileUpload("E:/tt/data","/admin/");
       boolean flag =  fileDownload("E:/tt/te/128","/admin/748/","748");
//       System.out.println(flag);
//        boolean flag = deleteDir("/admin/3128/");
//        boolean flag = deleteFile("/admin/2616/input/a0012.xml");
        System.out.println(flag);
    }

    /**
     * 
     *【功能描述:得到ftp 登陸結果 FtpClient】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @return
     * @throws IOException
     */
    public static FTPClient getFTPClient() throws IOException{
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ConfigReader.get("ftp.server",""));
        boolean flag = ftpClient.login(ConfigReader.get("ftp.username",""),
                ConfigReader.get("ftp.pwd",""));
        if(flag){
            ftpClient.setControlKeepAliveTimeout(ConfigReader.getInt("ftp.active.time", 600));
            return ftpClient;
        }else{
            return null;
        }
    }
    
    /**
     * 
     *【功能描述:上傳文件   和文件夾】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param filePath  上傳文件的路徑
     * @param ftpRePath 上傳後存儲的相對位置  eg:/admin/pic/
     * @return true, 只有當所有流程都成功才返回true ,不爲true就表示失敗
     */
     
    @SuppressWarnings("finally")
    public static boolean fileUpload(String filePath,String ftpRePath) {
        FTPClient ftpClient = new FTPClient();
        try {

            ftpClient = getFTPClient();
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("GBK");
            
            // 使用迭代器的方法以後,只會建立一個ftpClient 連接,方便ftp性能穩固
            iterateUpload(ftpClient,filePath,ftpRePath);
            
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP上傳失敗  ", e);
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("關閉FTP出現異常  ", e);
            }
            //當所有流程都成功以後返回成功
            return true;
        }
    }
    
    /**
     * 
     *【功能描述:上傳工具類,迭代】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param ftpClient
     * @param filePath
     * @param ftpRePath
     * @throws IOException
     */
    public static void iterateUpload(FTPClient ftpClient,String filePath,String ftpRePath) throws IOException{
        File srcFile = new File(filePath);
        // 原始上傳文件
        if(srcFile.isFile()){
            FileInputStream fis = new FileInputStream(srcFile);
            ftpClient.changeWorkingDirectory(ftpRePath);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.storeFile(srcFile.getName(), fis);
        }else if(srcFile.isDirectory()){
            // 只要是文件夾,就把當前文件夾的地址創建好。
            ftpClient.makeDirectory(ftpRePath+File.separator+srcFile.getName());
            File[] files = srcFile.listFiles();
            // 如果爲空,就只創建文件夾
            for(File f:files){
                iterateUpload(ftpClient,f.getAbsolutePath(),ftpRePath+File.separator+srcFile.getName());
            }
        }
    }

    /**
     * 
     *【功能描述:ftp 下載, 指定下載ftp上某一個目錄或者文件到本地】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param downloadPath 本地地址
     * @param dir ftp上文件地址(相對的如:/admin/rt/)
     * @param fileName ftp上要下載的文件名
     * @return true, 只有所有流程都成功才返回true, 不爲true就表示失敗
     */
     
    @SuppressWarnings("finally")
    public static boolean fileDownload(String downloadPath,String dir,String fileName) {
        FTPClient ftpClient = new FTPClient();

        try {
            ftpClient = getFTPClient();
            ftpClient.setBufferSize(1024);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            
            iterateDown(ftpClient,dir,downloadPath+File.separator+fileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP下載失敗  ", e);
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("關閉FTP連接失敗  ", e);
            }
            return true;
        }
    } 
    
    
    /**
     * 
     *【功能描述:下載功能的迭代器,】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param ftpClient ftpClient 連接器
     * @param dir ftp上的路徑
     * @param downloadPath 本地路徑
     * @throws IOException
     */
    public static void iterateDown(FTPClient ftpClient,String dir,String downloadPath) throws IOException{
        // 列出這個地址對應到的是文件夾還是文件
        FTPFile[] files = ftpClient.listFiles(dir);
        for(FTPFile f:files){
            //如果當前目錄還沒有創建,那麼就在這裏創建
            File filedown = new File(downloadPath);
            if(!filedown.exists()){
                filedown.mkdirs();
            }
            String localPath = downloadPath+File.separator+f.getName();
            File file = new File(localPath);
            if(f.isFile()){
                FileOutputStream fos = null;
                fos = new FileOutputStream(localPath);
                String path = dir+File.separator+f.getName();
                ftpClient.retrieveFile(path, fos);
                IOUtils.closeQuietly(fos);
            }else if(f.isDirectory()){
                file.mkdirs();
                iterateDown(ftpClient,dir+File.separator+f.getName(),localPath);
            }
        }
    }
    
    
    
    /**
     * 
     *【功能描述:刪除ftp 上指定的文件】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param ftpPath ftp上的文件路徑
     * @return true 成功,false,失敗
     */
    public static boolean deleteDir(String ftpPath){
        FTPClient ftpClient = new FTPClient();
        boolean flag = false;
        try {
            ftpClient = getFTPClient();
            ftpClient.setControlKeepAliveTimeout(ConfigReader.getInt("ftp.active.time", 600));
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            flag = iterateDelete(ftpClient,ftpPath);
            ftpClient.disconnect();
        } catch (IOException e) {
            // TODO 異常處理塊
            e.printStackTrace();
        }
        return flag;
    }
    
    /**
     * 
     *【功能描述:刪除文件夾】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param ftpClient
     * @param ftpPath  文件夾的地址
     * @return true 表似成功,false 失敗
     * @throws IOException
     */
    public static boolean iterateDelete(FTPClient ftpClient,String ftpPath) throws IOException{
        FTPFile[] files = ftpClient.listFiles(ftpPath);
        boolean flag = false;
        for(FTPFile f:files){
            String path = ftpPath+File.separator+f.getName();
            if(f.isFile()){
                // 是文件就刪除文件
                ftpClient.deleteFile(path);
            }else if(f.isDirectory()){
               iterateDelete(ftpClient,path);
            }
        }
        // 每次刪除文件夾以後就去查看該文件夾下面是否還有文件,沒有就刪除該空文件夾
        FTPFile[] files2 = ftpClient.listFiles(ftpPath); 
        if(files2.length==0){
            flag = ftpClient.removeDirectory(ftpPath);
        }else{
            flag = false;
        }
        return flag;
    }
    
    /**
     * 
     *【功能描述:刪除文件】
     *【功能詳細描述:功能詳細描述】
     * @see   【類、類#方法、類#成員】
     * @param filePath
     * @return
     */
    public static boolean deleteFile(String filePath){
        boolean flag = false;
        try {
            FTPClient ftpClient = getFTPClient();
            flag = ftpClient.deleteFile(filePath);
        } catch (IOException e) {
            // TODO 異常處理塊
            e.printStackTrace();
        }
        return flag;
        
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章