1. 程式人生 > >FTP伺服器檔案的上傳、拼接、下載

FTP伺服器檔案的上傳、拼接、下載

用到的包是 commons-net-1.4.1.jar , 可以通過maven下載,也可以在maven上直接下載匯入到專案。

1,工具類如下

package com.util.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;


/**
 * FTP工具類<br>
 * 方法包括:ftp連線、ftp檔案下載、上傳檔案到ftp、拼接ftp上的檔案內容
 * @author zsm
 *
 */
public class FtpUtil {

    /**
     * 獲取FTPClient物件
     *
     * @param ftpHost     FTP主機伺服器
     * @param ftpPassword FTP 登入密碼
     * @param ftpUserName FTP登入使用者名稱
     * @param ftpPort     FTP埠 預設為21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 連線FTP伺服器
            ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("未連線到FTP,使用者名稱或密碼錯誤。");
                ftpClient.disconnect();
            } else {
                System.out.println("FTP連線成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("FTP的IP地址可能錯誤,請正確配置。");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("FTP的埠錯誤,請正確配置。");
        }
        return ftpClient;
    }

    /**
     * 從FTP伺服器下載檔案
     *
     * @param ftpHost FTP IP地址
     * @param ftpUserName FTP 使用者名稱
     * @param ftpPassword FTP使用者名稱密碼
     * @param ftpPort FTP埠
     * @param ftpPath FTP伺服器中檔案所在路徑 格式: a/b
     * @param localPath 下載到本地的位置 格式:C:\\Users\\Administrator\\Desktop\\
     * @param fileName 檔名稱
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserName,
                                       String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                       String fileName) {

        FTPClient ftpClient = null;

        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("UTF-8"); // 中文編碼處理
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            File localFile = new File(localPath + File.separatorChar + fileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(fileName, os);
            os.close();
            ftpClient.logout();

        } catch (FileNotFoundException e) {
            System.out.println("沒有找到" + ftpPath + "檔案");
            e.printStackTrace();
        } catch (SocketException e) {
            System.out.println("連線FTP失敗.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("檔案讀取錯誤。");
            e.printStackTrace();
        }

    }

    /**
     * 向FTP伺服器上傳檔案
     * @param ftpHost FTP伺服器hostname
     * @param ftpUserName 賬號
     * @param ftpPassword 密碼
     * @param ftpPort 埠
     * @param ftpPath  FTP伺服器中檔案所在路徑 格式: a/b
     * @param fileName ftp檔名稱
     * @param input 檔案流 (檔案內容)
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadFile(String ftpHost, String ftpUserName,
                                     String ftpPassword, int ftpPort, String ftpPath,
                                     String fileName,InputStream input) {
        boolean success = false;
        FTPClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            ftpClient.setControlEncoding("UTF-8"); //中文編碼處理
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            ftpClient.storeFile(fileName, input);

            input.close();
            ftpClient.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
    /**
     * 如果伺服器沒有該檔案,會建立一個空檔案,如果存在該檔案,就將內容拼接到檔案中
     * @param ftpHost FTP伺服器hostname
     * @param ftpUserName 賬號
     * @param ftpPassword 密碼
     * @param ftpPort 埠
     * @param ftpPath  FTP伺服器中檔案所在路徑 格式: a/b
     * @param fileName ftp檔名稱
     * @param input 檔案流 (拼接的檔案內容)
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadAppendFile(String ftpHost, String ftpUserName,
                                     String ftpPassword, int ftpPort, String ftpPath,
                                     String fileName,InputStream input) {
        boolean success = false;
        FTPClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            ftpClient.setControlEncoding("UTF-8"); // 中文支援
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            ftpClient.appendFile(fileName, input);

            input.close();
            ftpClient.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }


}

2,測試類如下,測試中有的方法註釋了,開啟即可測試。

package com.util.ftp;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class Test {
    public static void main(String[] args) {
        String ftpHost = "192.168.0.102";
        String ftpUserName = "meng";
        String ftpPassword = "123456";
        int ftpPort = 21;
        String ftpPath = "/";
        
        //上傳  
        
        String localPath = "C:\\Users\\Administrator\\Desktop\\abc.txt";//本地要上傳的檔案
        String fileName = "abcdd.txt";//上傳到伺服器的名字,檔名可修改
        
        //下載  
//        String localPath = "C:\\Users\\Administrator\\Desktop\\";//本地儲存的地址
//        String fileName = "123.txt";//從伺服器下載的檔案

        //上傳一個檔案
//        try{
//            FileInputStream in=new FileInputStream(new File(localPath));
//            boolean test = FtpUtil222.uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName,in);
//            System.out.println(test);
//        } catch (FileNotFoundException e){
//            e.printStackTrace();
//            System.out.println(e);
//        }

        //在FTP伺服器上生成一個檔案,並將一個字串寫入到該檔案中
        try {
            //windows下的文字檔案換行符:\r\n   linux/unix下的文字檔案換行符:\r     Mac下的文字檔案換行符:\n
            InputStream input = new ByteArrayInputStream("test append\r\n".getBytes("utf-8"));
            boolean flag = FtpUtil.uploadAppendFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName,input);
            System.out.println(flag);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //下載一個檔案
       // FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
    }
}

3,如果檔案無法上傳,可能是ftp許可權問題,開啟讀寫許可權。

4,API地址:http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html

5,如果是在本地測試,推薦用ServU建立本地ftp服務站點。