1. 程式人生 > >【FTP】java實現FTP服務上傳下載

【FTP】java實現FTP服務上傳下載

1、首先在pom檔案中新增ftp相關依賴。

	<!--和FTP有關-->
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>3.3</version>
		</dependency>

2、程式碼庫如下

package com.zero.service.impl;

import com.zero.Shift;
import com.zero.StatusCode;
import com.zero.config.FtpConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.SocketException;

/**
 * Created by shuo on 2018/5/21.
 */
@Service("ftpService")
@Slf4j
public class FtpServiceImpl {

    public FTPClient ftpClient = null;
    public   FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) throws SocketException,IOException {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.setDataTimeout(60000);       //設定傳輸超時時間為60秒
        ftpClient.setConnectTimeout(60000);       //連線超時為60秒
        try {
            ftpClient.connect(ftpHost, ftpPort);// 連線FTP伺服器
            ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.error("未連線到FTP,使用者名稱或密碼錯誤。");
                ftpClient.disconnect();
            }
        } catch (SocketException e) {
            e.printStackTrace();
            throw new SocketException("FTP的IP地址可能錯誤,請正確配置。");
        } catch (IOException e) {
            e.printStackTrace();
            throw new SocketException("FTP的埠錯誤,請正確配置。");
        }
        return ftpClient;
    }


    /**
     * 上傳檔案
     * @param pathName ftp服務儲存地址
     * @param fileName 上傳到ftp的檔名
     *  @param originfilename 待上傳檔案的名稱(絕對地址) *
     * @return
     */
    public boolean uploadFile(FTPClient ftpClient,String orgId, String pathName, String fileName,String originfilename) throws Exception {
        InputStream inputStream = new FileInputStream(new File(originfilename));
        return uploadFile(ftpClient,pathName,fileName,inputStream);
    }
    /**
     * 上傳檔案
     * @param realPathName ftp服務儲存地址
     * @param uuidName 上傳到ftp的檔名
     * @param inputStream 輸入檔案流
     * @return
     */
    public boolean uploadFile(FTPClient ftpClient,String realPathName, String uuidName,InputStream inputStream) throws Exception{
        boolean flag=false;
        try{
            this.ftpClient=ftpClient;
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            createDirecroty(realPathName);
            ftpClient.makeDirectory(realPathName);
            ftpClient.changeWorkingDirectory(realPathName);
            ftpClient.storeFile(uuidName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag=true;
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("上傳檔案失敗");
        }finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                    throw new Exception("上傳檔案失敗");
                }
            }

        }
        return flag;
    }
    //改變目錄路徑
    public boolean changeWorkingDirectory(String directory) throws Exception {
        boolean flag = true;
        try {
            //flag = getDefaultFtpClient().changeWorkingDirectory(directory);
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                System.out.println("進入資料夾" + directory + " 成功!");

            } else {
                System.out.println("進入資料夾" + directory + " 失敗!開始建立資料夾");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw new Exception("改變目錄路徑失敗");
        }
        return flag;
    }

    //建立多層目錄檔案,如果有ftp伺服器已存在該檔案,則不建立,如果無,則建立

    public boolean createDirecroty(String remote) throws Exception {
        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("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                System.out.println("***************");
                System.out.println("subDirectory:"+subDirectory);
                System.out.println("path:"+path);
                //false表示當前資料夾下沒有檔案
                if (!existFile(path)) {
                    System.out.println("path:"+path+";existFile");
                    if (makeDirectory(subDirectory)) {
                        System.out.println("path:"+path+";makeDirectory");
                        changeWorkingDirectory(subDirectory);
                        System.out.println("path:"+path+";changeWorkingDirectory");
                    } else {
                        System.out.println("建立目錄[" + subDirectory + "]失敗");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    System.out.println("path:"+path+";changeWorkingDirectory1");
                    changeWorkingDirectory(subDirectory);
                    System.out.println("path:"+path+";changeWorkingDirectory2");
                }

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

    //判斷ftp伺服器檔案是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        //FTPFile[] ftpFileArr = getDefaultFtpClient().listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    //建立目錄
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
//            flag = getDefaultFtpClient().makeDirectory(dir);
            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  boolean downloadFile(FTPClient ftpClient,String pathName, String fileName, OutputStream os) throws Exception{
        boolean flag;
        //OutputStream os=null;
        try {
            System.out.println("開始下載檔案");
            this.ftpClient=ftpClient;
            //切換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) {
            e.printStackTrace();
            throw new Exception("下載檔案失敗");
        } finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                    throw new Exception("下載檔案失敗");
                }
            }
            if(null != os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new Exception("下載檔案失敗");
                }
            }
        }
        return flag;
    }

    /** * 刪除檔案 *
     * @param pathName FTP伺服器儲存目錄 *
     * @param fileName 要刪除的檔名稱 *
     * @return */
    public boolean deleteFile(FTPClient ftpClient,String pathName, String fileName) throws Exception{
        boolean flag;

        try {
            System.out.println("開始刪除檔案");
            this.ftpClient=ftpClient;
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathName);
            ftpClient.dele(fileName);
            ftpClient.logout();
            flag = true;
            System.out.println("刪除檔案成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("刪除檔案失敗");
        } finally {
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                    throw new Exception("刪除檔案失敗");
                }
            }
        }
        return flag;
    }
}

3、客戶端

       首先先獲取FTPClient物件。然後就可以進行上傳、下載、刪除等操作啦。需要注意的是ftpclient不支援一次建立多級目錄,因此需要通過迭代來建立多級目錄。建立多級目錄的時候需要保證是同一個物件