1. 程式人生 > >java 操作FTP進行檔案操作

java 操作FTP進行檔案操作

package com.ding.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.SocketException;
import java.util.Properties;

/**
 * Created by ding on 1/16/16.
 */
public class FTPClientUtils {
    private  static Logger logger = Logger.getLogger(FTPClientUtils.class);
    public static String FTPCONFIG= "config/ftpConfig.properties";
    private static  FTPClient ftpClient = null; //FTP 客戶端代理

    //Get FTP config
    public static String getFTPSetting(String key){
        String value="";
        String path =FTPClientUtils.class.getClassLoader().getResource("").getPath() + FTPCONFIG;
        try {
            Properties properties = new Properties();
            InputStream in = new FileInputStream(path);
            BufferedReader bis = new BufferedReader(new InputStreamReader(in,"UTF-8"));
            properties.load(bis);
            value = properties.getProperty(key);
        }catch (IOException e){
            logger.info(" ftp 配置檔案解析error:",e);
            e.printStackTrace();
        }
        return value;
    }



    //open FTP connection,return true=success ,false=failure
    public static  boolean openConnectFTPService() {
        boolean flag = true;
        try {
            ftpClient = new FTPClient();
//        FTPClientConfig config = new FTPClientConfig();
//        config.setXXX(YYY); // change required options
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.setDefaultPort(Integer.parseInt(getFTPSetting("port")));
            ftpClient.connect(getFTPSetting("ip"),Integer.parseInt(getFTPSetting("port")));
            ftpClient.login(getFTPSetting("username"), getFTPSetting("password"));
            int reply = ftpClient.getReplyCode();
            ftpClient.setDataTimeout(Integer.parseInt(getFTPSetting("dataTimeOut")));
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                logger.info("FTP伺服器拒絕連線!");
                flag = false;
            }
            System.err.println("FTP server  connection success.");
        } catch (SocketException e){
            logger.info("登陸FTP伺服器ip:"+getFTPSetting("ip")+"失敗,連線超時.",e);
            flag = false;
            e.printStackTrace();
        }catch (IOException e){
            flag = false;
            logger.info("登陸FTP伺服器ip:"+getFTPSetting("ip")+"失敗,FTP伺服器無法開啟!",e);
            e.printStackTrace();
        }
        return flag;
    }
    //close FTP connection
    public  static void closeConnection(){
        try {
            if (ftpClient!=null){
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }catch (IOException e){
            logger.info("FTP service close exception:",e);
            e.printStackTrace();
        }

    }


    /**
     * 列出伺服器上所有的檔案和目錄
     * @return
     */
    public static void ListNamesAll(){
        try{
            String[] files = ftpClient.listNames();
            if (files ==null||files.length==0){
                System.out.println("沒有任何檔案");
            }else {
                for( int i = 0 ; i<files.length;i++){
                    System.out.println(files[i]);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }



    /**
     * 刪除一個檔案
     */
    public static boolean deleteFile(String filename) {
        boolean flag = true;
        try {
            flag = ftpClient.deleteFile(filename);
            if (flag) {
                System.out.println("刪除檔案成功!");
            } else {
                System.out.println("刪除檔案失敗!");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    /**
     * 待定:有問題
     * 刪除FTP目錄(包括此目錄中的所有檔案)
     */
    public static void deleteDirectory(String pathname) {
        try {
            openConnectFTPService();
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.changeToParentDirectory();//上一層目錄
            String[] files = ftpClient.listNames();
            for( int i = 0 ; i<files.length;i++){
                System.out.println(files[i]);
            }
            ftpClient.removeDirectory(pathname);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 刪除空目錄
     */
    public static void deleteEmptyDirectory(String pathname) {
        try {
            openConnectFTPService();
            ftpClient.removeDirectory(pathname);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 進入到伺服器的某個目錄下
     *
     * @param directory
     */
    public static void changeWorkingDirectory(String directory) {
        try {
            openConnectFTPService();
            ftpClient.changeWorkingDirectory(directory);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 返回到上一層目錄
     */
    public static void changeToParentDirectory() {
        try {
            openConnectFTPService();
            ftpClient.changeToParentDirectory();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 重新命名檔案
     *
     * @param oldFileName --原檔名
     * @param newFileName --新檔名
     */
    public static void renameFile(String oldFileName, String newFileName) {
        try {
            openConnectFTPService();
            ftpClient.rename(oldFileName, newFileName);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 在伺服器上建立一個目錄,噹噹前路徑不存在依次建立子目錄(資料夾)
     * @param dir 資料夾名稱,不能含有特殊字元,如 \ 、/ 、: 、* 、?、 "、 <、>...
     */
    public static boolean makeDirectory(String dir) {
        openConnectFTPService();
        boolean flag = true;
        try {
            File file = new File(dir);
            if (!file.isDirectory()){
                String[] str = dir.split("/");
                System.out.println(str.length);
                String dirPath = "";
                for (int i=0;i<str.length;i++) {
                    dirPath += "/"+str[i];
                    boolean directory = ftpClient.changeWorkingDirectory(dirPath);
                    if(!directory){//當directory為false,則建立FTP當前路徑
                        flag = ftpClient.makeDirectory(dirPath);
                    }
                }
                if (flag) {
                    System.out.println("make Directory " + dir + " succeed");
                } else {
                    System.out.println("make Directory " + dir + " false");
                }
            }else{
                System.out.println(dir+"不是一個目錄");
            }

        }catch (IOException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 轉碼[ISO-8859-1 -> GBK] 不同的平臺需要不同的轉碼
     *
     * @param obj
     * @return ""
     */
    private static String iso8859togbk(Object obj) {
        try {
            if (obj == null)
                return "";
            else
                return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 設定傳輸檔案的型別[文字檔案或者二進位制檔案]
     * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
     */
    public static void setFileType(int fileType) {
        try {
            ftpClient.setFileType(fileType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下載檔案
     *
     * @param remoteFileName             --伺服器上的檔名
     * @param localFileName--本地檔名
     * @return true 下載成功,false 下載失敗
     */
    public static boolean downloadFile(String remoteFileName, String localFileName) {
        boolean flag = true;
//        openConnectFTPService();
        // 下載檔案
        BufferedOutputStream buffOut = null;
        try {
            flag = ftpClient.retrieveFile(remoteFileName, buffOut);
            buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("本地檔案下載失敗!", e);
        } finally {
            try {
                if (buffOut != null)
                    buffOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 上傳單個檔案,並重命名
     * @param localFile--本地檔案路徑
     * @param remoteFileName--新的檔名,可以命名為空""
     * @param saveRemoteFolderPath--FTP伺服器上傳儲存資料夾的路徑
     * @return true 上傳成功,false 上傳失敗
    */
    public static boolean uploadFile(File localFile,String remoteFileName,String saveRemoteFolderPath) {
        boolean flag = true;
        try {
            InputStream input = new FileInputStream(localFile);
            if (input == null) {
                System.out.println("本地檔案"+localFile.getPath()+"不存在!");
            }
            openConnectFTPService();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            //進入FTP當前資料夾,當資料夾不存在則false
            boolean remoteFolder =ftpClient.changeWorkingDirectory(saveRemoteFolderPath);
            if (!remoteFolder){
                boolean IsCreatedFolder = makeDirectory(saveRemoteFolderPath);
                if(!IsCreatedFolder){
                    logger.info(saveRemoteFolderPath+"路徑在FTP伺服器上面不存在");
                    System.out.println("路徑在FTP伺服器上面不存在!");
                }
                ftpClient.changeWorkingDirectory(saveRemoteFolderPath);
            }
            flag = ftpClient.storeFile(remoteFileName, input);
            if (flag) {
                System.out.println("上傳檔案成功!");
            } else {
                System.out.println("上傳檔案失敗!");
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("本地檔案上傳失敗!", e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 上傳單個檔案,並重命名
     * @param input--檔案流
     * @param remoteFileName--新的檔名,可以命名為空""
     * @param saveRemoteFolderPath--FTP伺服器上傳儲存資料夾的路徑
     * @return true 上傳成功,false 上傳失敗
     */
    public static boolean inputStreamUploadFile(InputStream input,String remoteFileName,String saveRemoteFolderPath) {
        boolean flag = true;
        try {
            if (input == null) {
                System.out.println("本地檔案不存在!");
            }
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            //進入FTP當前資料夾,當資料夾不存在則false
            boolean remoteFolder =ftpClient.changeWorkingDirectory(saveRemoteFolderPath);
            if(!remoteFolder){
                boolean IsCreatedFolder = makeDirectory(saveRemoteFolderPath);
                if(!IsCreatedFolder){
                    logger.info(saveRemoteFolderPath+"路徑在FTP伺服器上面不存在");
                    System.out.println("路徑在FTP伺服器上面不存在!");
                }
                ftpClient.changeWorkingDirectory(saveRemoteFolderPath);
            }
            flag = ftpClient.storeFile(remoteFileName, input);
            if (flag) {
                System.out.println("上傳檔案成功!");
            } else {
                System.out.println("上傳檔案失敗!");
            }
            input.close();
        } catch (IOException e) {
            flag = false;
            e.printStackTrace();
            logger.debug("本地檔案上傳失敗!", e);
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }
}
配置檔案:
<pre style="background-color:#2b2b2b;color:#a9b7c6;font-family:'Source Code Pro';font-size:12.0pt;"><span style="color:#808080;">########################################
</span><span style="color:#808080;">##  FTP setting
</span><span style="color:#808080;">#########################################
</span><span style="color:#cc7832;">ip</span><span style="color:#808080;">=</span><span style="color:#6a8759;">192.168.1.151
</span><span style="color:#808080;">#ip=192.168.120.57
</span><span style="color:#cc7832;">port</span><span style="color:#808080;">=</span><span style="color:#6a8759;">21
</span><span style="color:#cc7832;">username</span><span style="color:#808080;">=</span><span style="color:#6a8759;">ubuntu
</span><span style="color:#cc7832;">password</span><span style="color:#808080;">=123456</span><span style="color:#6a8759;">
</span><span style="color:#cc7832;">dataTimeOut</span><span style="color:#808080;">=</span><span style="color:#6a8759;">12000
</span><span style="color:#6a8759;">
</span><span style="color:#808080;">##</span><span style="color:#808080;font-family:'AR PL UKai CN';">訪問路徑
</span><span style="color:#cc7832;">visitPath</span><span style="color:#808080;">=</span><span style="color:#6a8759;">http://192.168.10.151:8080/ftp
</span><span style="color:#cc7832;">ftpStore</span><span style="color:#808080;">=</span><span style="color:#6a8759;">/home/ubuntu/uftp
</span><span style="color:#808080;">#ftpStore=/
</span><span style="color:#808080;">
</span><span style="color:#cc7832;">modelPath</span><span style="color:#808080;">=</span><span style="color:#6a8759;">model
</span><span style="color:#cc7832;">firmwarePath</span><span style="color:#808080;">=</span><span style="color:#6a8759;">firmware
</span><span style="color:#cc7832;">pluginPath</span><span style="color:#808080;">=</span><span style="color:#6a8759;">plugin
</span>