天天看點

apache FtpClient上傳下載下傳删除檔案夾及檔案

/*

 * 檔案名:FtpUtil.java

 * 描述:FTP操作

 * 修改時間2014-08-10

 */

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Arrays;

import java.util.Calendar;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPClientConfig;

import org.apache.commons.net.ftp.FTPFile;

import org.apache.commons.net.ftp.FTPReply;

/**

 * FTP操作,主要用于上傳檔案、下載下傳檔案、删除檔案及檔案夾、擷取檔案加下檔案名字清單

 * 

 * @author

 * @version 1.0

 * @see

 * @since

public class FtpUtil

{

    // 日志

    private static Log logger = LogFactory.getLog(FtpUtil.class);

    // FTPClient對象

    private FTPClient ftp;

    // ftp ip位址

    private String ftpServer;

    // ftp登入端口号

    private String ftpPort;

    // 登入使用者名

    private String userName;

    // 登入密碼

    private String password;

    public void setFtpServer(String ftpServer)

    {

        this.ftpServer = ftpServer;

    }

    public void setFtpPort(String ftpPort)

        this.ftpPort = ftpPort;

    public void setPassword(String password)

        this.password = password;

    public void setUserName(String userName)

        this.userName = userName;

    public FtpUtil(String ftpServer, String ftpPort, String userName, String password)

    /**

     * 連接配接Ftp伺服器

     * 

     * @return SUCCESS:成功 其他:失敗資訊

     * @see [類、類#方法、類#成員] Create Author:> Time:<Aug 30, 2014> Ver:< >

     */

    public String loginToFtpServer()

        if (null == ftp)

        {

            try

            {

                ftp = new FTPClient();

                // 不設端口 預設使用預設端口登入21

                if (CommonUtil.isEmpty(ftpPort))

                {

                    ftp.connect(this.ftpServer);

                }

                else

                    ftp.connect(this.ftpServer, Integer.parseInt(ftpPort));

                //下面三行代碼必須要有,而且不能改變編碼格式否則不能正确下載下傳中文檔案

                ftp.setControlEncoding("GBK");

                FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);   

                conf.setServerLanguageCode("zh"); 

                //驗證通道連接配接是否建立成功(回傳響應碼)

                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))

                    ftp.disconnect();

                    logger.error("FTP連接配接失敗,ip:" + this.ftpServer);

                    return "FTP連接配接失敗,ip:" + this.ftpServer;

                //登入

                if (!ftp.login(this.userName, this.password))

                    logger.error("FTP登入失敗,ip:" + this.ftpServer + ";userName:" + userName + ";port:" + ftpPort);

                    return "FTP登入失敗,ip:" + this.ftpServer + ";userName:" + userName + ";port:" + ftpPort;

            }

            catch (Exception e)

                logger.error("FTP連接配接失敗", e);

                return "FTP連接配接失敗" + e;

        }

        logger.info("Ftp" + this.ftpServer + "登入成功!;port:" + ftpPort);

        return CommonProperties.SUCCESS;

     * 關閉ftp連接配接 <功能較長的描述> void

     * @see [類、類#方法、類#成員] Create Author:<> Time:<Aug 30, 2014> Ver:< >

    public void closeConnection()

        if (null != ftp && ftp.isConnected())

                ftp.disconnect();

                logger.info("FTP"+this.ftpServer+"連接配接關閉");

                logger.error("FTP連接配接關閉異常", e);

     * 上傳檔案到ftp <功能較長的描述>

     * @param remotePath ftp路徑

     * @param remoteName 檔案名

     * @param localFile 要上傳的本地檔案

     * @return SECCESS:上傳成功 其他:上傳失敗資訊

     * @see [類、類#方法、類#成員] Create Author:<> Time:<Aug 19, 2014> Ver:< >

    public String uploadFile(String remotePath, String localFileName)

        FileInputStream in = null;

        try

            // 存放在Ftp上的檔案名稱

            String remoteFileName = "";

            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            if (CommonUtil.isEmpty(localFileName) || CommonUtil.isEmpty(remotePath))

                logger.error("檔案上傳Ftp失敗目标路徑或源路徑錯誤");

                return "檔案上傳Ftp失敗目标路徑或源路徑錯誤";

            remoteFileName = localFileName.substring(localFileName.lastIndexOf("/")+1, localFileName.length());

            // 確定檔案路徑存在

            ftp.makeDirectory(remotePath);

            if (!ftp.changeWorkingDirectory(remotePath))

                logger.error("轉至目錄[" + remotePath + "]失敗");

                return "轉至目錄[" + remotePath + "]失敗";

            // 上傳之前先删除原來檔案,防止重複對賬(檔案不存不報異常)

            ftp.deleteFile(remoteFileName);

            in = new FileInputStream(new File(localFileName));

            ftp.storeFile(new String(remoteFileName.getBytes("GBK"), "iso-8859-1"), in);

        catch (Exception e)

            logger.error("檔案上傳Ftp失敗:", e);

            return "檔案上傳Ftp失敗:" + e;

        finally

            CommonUtil.closeStream(in);

     * 擷取檔案夾下檔案名稱清單 <功能較長的描述>

     * @param remotePath 檔案夾路徑

     * @return List<String> 檔案名稱清單

     * @see [類、類#方法、類#成員] Create Author:<> Time:<Aug 20, 2014> Ver:< >

    public List<String> getFileList(String remotePath)

            if (ftp.changeWorkingDirectory(remotePath))

                String[] str = ftp.listNames();

                if (null == str || str.length < 0)

                    return null;

                return Arrays.asList(str);

        catch (IOException e)

            e.printStackTrace();

        return null;

     * 從Ftp下載下傳檔案 <功能較長的描述>

     * @param remotePath Ftp上檔案路徑

     * @param remoteFileName 遠端檔案名

     * @param localFileName 下載下傳到本地檔案路徑(帶檔案名)

    public String download(String remotePath, String remoteFileName, String localFileName)

        FileOutputStream oStream = null;

            // 切換到指定目錄下

                oStream = new FileOutputStream(new File(localFileName));

                if (!ftp.retrieveFile(remoteFileName, oStream))

                    logger.info("從Ftp上下載下傳檔案失敗!" + remoteFileName);

                    return "從Ftp上下載下傳檔案失敗!" + remoteFileName;

            else

                logger.info("對賬檔案下載下傳失敗,不能正常切換至目錄" + remotePath + ";目錄不存在!");

                return "對賬檔案下載下傳失敗,不能正常切換至目錄" + remotePath + ";目錄不存在!";

            logger.info("Ftp上檔案" + remoteFileName + "下載下傳失敗!", e);

            return "Ftp上檔案" + remoteFileName + "下載下傳失敗!" + e;

            CommonUtil.closeStream(oStream);

     * 删除Ftp上的檔案夾 包括其中的檔案 <功能較長的描述>

     * @param client Ftp對象

     * @param pathName 檔案夾路徑

     * @return SUCCESS:成功 其他:失敗

     * @see [類、類#方法、類#成員] Create Author:<> Time:<Aug 18, 2014> Ver:< >

    public String removeDirectoryALLFile(String pathName)

            FTPFile[] files = ftp.listFiles(pathName);

            if (null != files && files.length > 0)

                for (FTPFile file : files)

                    if (file.isDirectory())

                    {

                        removeDirectoryALLFile(pathName + "/" + file.getName());

                        // 切換到父目錄,不然删不掉檔案夾

                        ftp.changeWorkingDirectory(pathName.substring(0, pathName.lastIndexOf("/")));

                        ftp.removeDirectory(pathName);

                    }

                    else

                        if (!ftp.deleteFile(pathName + "/" + file.getName()))

                        {

                            return "删除指定檔案" + pathName + "/" + file.getName() + "失敗!";

                        }

            // 切換到父目錄,不然删不掉檔案夾

            ftp.changeWorkingDirectory(pathName.substring(0, pathName.lastIndexOf("/")));

            ftp.removeDirectory(pathName);

            logger.error("删除指定檔案夾" + pathName + "失敗:" + e);

            return "删除指定檔案夾" + pathName + "失敗:" + e;

     * 删除指定檔案

     * @param filePath 檔案路徑(含檔案名)

     * @see [類、類#方法、類#成員]

    public String removeFile(String filePath)

            if (StringUtils.isNotEmpty(filePath))

                if (!ftp.deleteFile(filePath))

                    return "删除檔案" + filePath + "失敗!";

            logger.error("删除檔案失敗:", e);

            return "删除檔案" + filePath + "失敗!" + e;

     * 向檔案頭添加合計資訊

     * @param localPath 目标檔案所在檔案夾路徑

     * @param desFile 目标檔案名

     * @param mergeStr 插入字元串資訊

    public static String mergeFile(String localPath, String desFile, String mergeStr)

        // 向目标檔案頭中添加合計資訊

        FileInputStream inputStream = null;

        FileOutputStream fileOutStream = null;

            inputStream = new FileInputStream(localPath + "/" + desFile);

            byte allBytes[] = new byte[inputStream.available()];

            inputStream.read(allBytes);

            fileOutStream = new FileOutputStream(localPath + "/" + desFile);

            fileOutStream.write(mergeStr.getBytes());

            fileOutStream.write(allBytes);

            return e.getMessage();

            CommonUtil.closeStream(fileOutStream);

            CommonUtil.closeStream(inputStream);

     * 删除備份目錄下不符合時間的檔案 <功能較長的描述>

     * @param dailyBakPath 備份目錄

     * @param dailyBakDate 有效時間 1、5、9等

    public static String deleteFile(String dailyBakPath, String dailyBakDate)

            // 擷取符合規則的日期

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

            // 當天時間

            Calendar theday = Calendar.getInstance();

            // 存放符合備份的日期時間 數組長度為備份的天數+1

            String[] dates = new String[Integer.valueOf(dailyBakDate) + 1];

            for (int i = 0; i < dates.length; i++)

                dates[i] = df.format(theday.getTime());

                // 擷取上一天的時間

                theday.add(Calendar.DATE, -1);

            File a = new File(dailyBakPath);

            if (!a.exists())

                return dailyBakPath + "目錄不存在!";

            // 擷取目錄下所有檔案

            String[] fileArr = a.list();

            // 周遊檔案名稱,檢視是否在保留日期dates内,不在則删除

            for (int i = 0; i < fileArr.length; i++)

                boolean canDele = true;

                for (int j = 0; j < dates.length; j++)

                    // 不删除dates内開頭的檔案 和 檔案名包含error的檔案

                    if (fileArr[i].startsWith(dates[j]) || fileArr[i].contains("error"))

                        canDele = false;

                        break;

                if (canDele)

                    deletefile(dailyBakPath + "/" + fileArr[i]);

            logger.info("删除檔案夾内容操作出錯,請檢視配置路徑或保留時間是否正确!");

            return "删除檔案夾内容操作出錯,請檢視配置路徑或保留時間是否正确!";

     * 根據入參,删除檔案夾(下檔案及檔案夾)或檔案

     * @param delpath 檔案夾路徑或檔案路徑

     * @return boolean true:成功 false:失敗

    public static boolean deletefile(String delpath)

            File file = new File(delpath);

            if (file.isDirectory())

                String[] filelist = file.list();

                for (int i = 0; i < filelist.length; i++)

                    // 遞歸調用

                    deletefile(delpath + "\\" + filelist[i]);

            // 删除

            file.delete();

            logger.error("deletefile() Exception:" + e.getMessage());

        return true;

    public static void main(String[] args) throws IOException

         //System.out.println(deletefile("G:/Q"));

         FtpUtil ftpUtil = new FtpUtil("192.168.132.110", "21", "a", "a");

         System.out.println(ftpUtil.loginToFtpServer());

         // System.out.println(ftpUtil.removeDirectoryALLFile("/home/tbcs/zhangvb/epay/20140820"));

        // FTPClient client=new FTPClient();

        // client.connect("192.168.132.110");

        // client.login("a","a");

        // System.out.println(client.removeDirectory("/home/tbcs/zhangvb/epay/test"));

下一篇: About Me