Java調用FTP


算是一個工具類吧,網上示例挺多,貼一個看到的比較好的示例,修改了很小一部分有問題的地方,並附上鏈接。中間比較惡心的是沒有判定目錄是否存在的api,只能通過枚舉進行判斷。

一、引入依賴

<!--commons-net -->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.5</version>
</dependency>

二、創建工具類FtpUtils

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.MalformedURLException;

/**
 * @Auther: hrabbit
 * @Date: 2018-04-21 下午12:35
 * @Description:
 */
public class FTPUtils {

    public static FTPClient ftpClient = null;

    /**
     * 初始化ftp服務器
     */
    public static void initFtpClient(String hostname,String username,String password,Integer port) {
        ftpClient = new FTPClient();
        /**
         * 在上傳文件的時候,我們的文件名稱有時候需要被保留,但是有時候如果文件名稱為中文的話,會產生保存失敗的現象,因此只需要將FTPClient的編碼方式更改為UTF-8模式即可解決
         */
        ftpClient.setControlEncoding("utf-8");
        try {
            //連接ftp服務器
            ftpClient.connect(hostname, port);
            //登錄ftp服務器
            ftpClient.login(username, password);
            //是否成功登錄服務器
            int replyCode = ftpClient.getReplyCode();
            if(FTPReply.isPositiveCompletion(replyCode)){
                System.out.println("ftp服務器登錄成功");
            }
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上傳文件
     * @param pathname ftp服務保存地址
     * @param fileName 上傳到ftp的文件名
     * @param inputStream 輸入文件流
     * @return
     */
    public static boolean uploadFile(String hostname,String username,String password,Integer port, String pathname, String fileName,InputStream inputStream){
        boolean flag = false;
        try{
            System.out.println("開始上傳文件");
            initFtpClient(hostname,username,password,port);
            /**
             * 二進制形式上傳文件
             */
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            /**
             * 主動模式和被動模式的不同簡單概述為: 主動模式傳送數據時是“服務器”連接到“客戶端”的端口;被動模式傳送數據是“客戶端”連接到“服務器”的端口。

				主動模式需要客戶端必須開放端口給服務器,很多客戶端都是在防火牆內,開放端口給FTP服務器訪問比較困難。

				被動模式只需要服務器端開放端口給客戶端連接就行了。

				因此只需要將模式改為被動模式即可:
             */
            ftpClient.enterLocalPassiveMode();
            CreateDirecroty(pathname);
//            ftpClient.makeDirectory(pathname);
            ftpClient.setControlEncoding("utf-8");
            ftpClient.storeFile(fileName, inputStream);
            System.out.println("上傳結束");
            inputStream.close();
            ftpClient.logout();
            flag = true;
            System.out.println("上傳文件成功");

        }catch (Exception e) {
            System.out.println("上傳文件失敗");
            e.printStackTrace();
        }finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
    //改變目錄路徑
    public static boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                System.out.println("進入文件夾" + directory + " 成功!");
            } else {
                System.out.println("進入文件夾" + directory + " 失敗!開始創建文件夾");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //創建多層目錄文件,如果有ftp服務器已存在該文件,則不創建,如果無,則創建
    public static boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("UTF-8"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("創建目錄[" + subDirectory + "]失敗");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 檢查所有目錄是否創建完畢
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    //判斷ftp服務器文件是否存在
    public static boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }
    //創建目錄
    public static boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                System.out.println("創建文件夾" + dir + " 成功!");

            } else {
                System.out.println("創建文件夾" + dir + " 失敗!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /** * 下載文件 *
     * @param pathname FTP服務器文件目錄 *
     * @param filename 文件名稱 *
     * @param localpath 下載后的文件路徑 *
     * @return */
    public static  boolean downloadFile(String hostname,String username,String password,Integer port,String pathname, String filename, String localpath){
        boolean flag = false;
        OutputStream os=null;
        try {
            System.out.println("開始下載文件");
            initFtpClient(hostname,username,password,port);
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for(FTPFile file : ftpFiles){
                if(filename.equalsIgnoreCase(file.getName())){
                    File localFile = new File(localpath + "/" + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            System.out.println("下載文件成功");
        } catch (Exception e) {
            System.out.println("下載文件失敗");
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /** * 刪除文件 *
     * @param pathname FTP服務器保存目錄 *
     * @param filename 要刪除的文件名稱 *
     * @return */
    public static boolean deleteFile(String hostname,String username,String password,Integer port,String pathname, String filename){
        boolean flag = false;
        try {
            System.out.println("開始刪除文件");
            initFtpClient(hostname,username,password,port);
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            System.out.println("刪除文件成功");
        } catch (Exception e) {
            System.out.println("刪除文件失敗");
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
}

三、愉快的使用吧

附鏈接:https://www.jianshu.com/p/44d9b05691a8

再附一個CSDN的:https://blog.csdn.net/crl2518528/article/details/71266728

四、吐個槽

csdn商業化也太明顯了吧,我想搜幾本電子書,出來全各種要積分的,以前的開源精神都去哪了,唉~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM