java網絡編程(4):FTP

第0章:簡介

     FTP是TCP/IP網絡上兩臺計算機傳送文件的協議。FTP客戶機可以給服務器發出命令來下載文件,上傳文件,創建或改變服務器上的目錄。FTP服務一般運行在20和21兩個端口。端口20用於在客戶端服務器之間傳輸數據流,而端口21用於傳輸控制流,並且是命令通向ftp服務器的進口。當數據通過數據流傳輸時,控制流處於空閒狀態。而當控制流空閒很長時間後,客戶端的防火牆會將其會話置爲超時,這樣當大量數據通過防火牆時,會產生一些問題。此時,雖然文件可以成功的傳輸,但因爲控制會話會被防火牆斷開,傳輸會產生一些錯誤。(來源:百度百科)


第0節:Apache commons-net.jar包簡介

(1)maven座標:

        <!-- Apache 網絡協議客戶端 -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.3</version>
        </dependency>

(2)參考:

官網:http://commons.apache.org/proper/commons-net/

項目地址:http://commons.apache.org/proper/commons-net/download_net.cgi


第1節:札記


第1章:實例

FTP服務處理工具類(FtpClientHandler.java),用到commons-net.jar包:


package com.mcc.core.net;

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ftp服務處理工具類,用到commons-net.jar包
 *
 * @author <a href="mailto:[email protected]">menergy</a>
 *         DateTime: 14-2-20  上午11:03
 */
public class FtpClientHandler {
    // 服務器名

    private String ftpServer = null;
    // 端口
    private int ftpPort = 21;
    // 用戶名
    private String ftpUser = null;
    // 密碼
    private String ftpPassword = null;
    // client
    private FTPClient ftpClient = null;
    //是否準備就緒,ture表示已經連接並登錄
    private boolean ready = false;

    /**
     *  構造器
     */
    public FtpClientHandler(String ftpServer, int ftpPort, String ftpUser, String ftpPassword) {
        this.ftpServer = ftpServer;
        this.ftpPort = ftpPort;
        this.ftpUser = ftpUser;
        this.ftpPassword = ftpPassword;

        init();
    }

    /**
     *  構造器
     */
    public FtpClientHandler(String ftpServer, String ftpUser, String ftpPassword) {
        this.ftpServer = ftpServer;
        this.ftpUser = ftpUser;
        this.ftpPassword = ftpPassword;

        init();
    }

    public void init() {
        ftpClient = new FTPClient();
    }

    /**
     * 連接FTP服務器端
     *
     * @throws java.io.IOException
     * @throws IllegalStateException
     */
    public void connectFtpServer() throws IllegalStateException, IOException{
        if (connect() && login()) {
            System.out.println("Success to connet and login server!");
            ready = true;
        }
    }

    /**
     * 連接服務器
     * @return
     * @throws IOException
     */
    private boolean connect() throws IOException {
        System.out.println("Try to connect server:" + ftpServer + " on port:" + ftpPort + " ... ... ");
        ftpClient.connect(ftpServer, ftpPort);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.out.println("Can not connet server:" + ftpServer + " on port:" + ftpPort);
            return false;
        }
        System.out.println("Success to connet server:" + ftpServer + " on port:" + ftpPort);
        return true;
    }

    /**
     * 權限認證
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        System.out.println("Try to login username:" + ftpUser + " ... ... ");
        boolean loginSuccess = ftpClient.login(ftpUser, ftpPassword);
        if (!loginSuccess) {
            ftpClient.logout();
            System.out.println("Fail to login username:" + ftpUser);
            return false;
        }
        System.out.println("Success to login username:" + ftpUser);
        return true;
    }

    /**
     * 斷開與FTP服務器的連接
     *
     * @throws IOException
     * @throws IllegalStateException
     */
    public void closeConnect() throws IllegalStateException, IOException {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上傳文件到FTP服務器
     *
     * @param localDir
     *            本地文件所在的目錄
     * @param localFileName
     *            本地要上傳的文件的文件名
     * @param remoteDir
     *            遠程的上存目錄
     *@param remoteFileName
     *            遠程的上傳文件名
     * @throws IOException
     * @throws IllegalStateException
     */
    public boolean upload(String localDir, String localFileName, String remoteDir ,String remoteFileName) throws IllegalStateException, IOException{
        if (!ready) {
            throw new RuntimeException("尚未連接登錄!");
        }
        File localFile = null;
        ftpClient.changeWorkingDirectory(remoteDir);
        if (!localDir.endsWith("\\") && !localDir.endsWith("/")) {
            localDir = localDir + "/";
        }
        localFile = new File(localDir + localFileName);

        /**
         * 判斷文件是否存在
         */
        if (localFile.exists()) {
            if(remoteFileName == null || "".equals(remoteFileName.trim())){
                remoteFileName = localFileName;
            }
            return ftpClient.storeFile(remoteFileName,new FileInputStream(localFile));
        } else {
            throw new IOException("can't find the file " + localDir + localFileName);
        }
    }

    /**
     * 上傳文件到FTP服務器,上存的文件名和原文件名一樣
     *
     * @param localDir
     *            本地文件所在的目錄
     * @param localFileName
     *            本地要上傳的文件的文件名
     * @param remoteDir
     *            遠程的上存目錄
     * @throws IOException
     * @throws IllegalStateException
     */
    public boolean upload(String localDir, String localFileName, String remoteDir) throws IllegalStateException, IOException{
        return upload(localDir, localFileName, remoteDir ,null);
    }

    /**
     * 下載遠程FTP服務器的文件到本地
     *
     * @param remoteDir
     *            遠程的目錄
     * @param remoteFileName
     *            遠程要下載的文件的文件名
     * @param localDir
     *            本地存文件的目錄
     * @param localFileName
     *            本地存文件的名字
     * @throws IOException
     * @throws IllegalStateException
     */
    public boolean download(String remoteDir, String remoteFileName, String localDir, String localFileName) throws IllegalStateException, IOException {
        if (!ready) {
            throw new RuntimeException("尚未連接登錄!");
        }
        File localFile = null;

        ftpClient.changeWorkingDirectory(remoteDir);

        if (!localDir.endsWith("\\") && !localDir.endsWith("/")) {
            localDir = localDir + "/";
        }

        if(localFileName == null || "".equals(localFileName.trim())){
           localFileName = remoteFileName;
        }
        localFile = new File(localDir + localFileName);

        /**
         * 判斷文件是否存在,存在的話就刪掉
         */
        if (localFile.exists()) {
            localFile.delete();
        }
        return ftpClient.retrieveFile(remoteFileName,new FileOutputStream(localFile));
    }

    /**
     * 下載遠程FTP服務器的文件到本地,下載的文件名和服務器中文件名一樣
     *
     * @param remoteDir
     *            遠程的目錄
     * @param remoteFileName
     *            遠程要下載的文件的文件名
     * @param localDir
     *            本地存文件的目錄
     * @throws IOException
     * @throws IllegalStateException
     */
    public boolean download(String remoteDir, String remoteFileName, String localDir) throws IllegalStateException, IOException {
        return download(remoteDir, remoteFileName, localDir,null);
    }

    /**
     * 在FTP遠程機上,刪除一個目錄
     *
     * @param remoteDir
     *            可以是絕對路徑或相對路徑
     * @throws IllegalStateException
     * @throws IOException
     */
    public void deleteDirectory(String remoteDir) throws IllegalStateException, IOException {
        ftpClient.dele(remoteDir);
    }

    /**
     * 在FTP遠程機上,建立一個目錄
     *
     * @param remoteDir
     *            遠程機的路徑
     * @param dirName
     *            目錄名
     * @throws IOException
     * @throws IllegalStateException
     */
    public boolean mkDir(String remoteDir, String dirName) throws IllegalStateException, IOException {
        ftpClient.changeWorkingDirectory(remoteDir);
        return ftpClient.makeDirectory(dirName);
    }

    /**
     * 在FTP遠程機上,刪除文件
     *
     * @param remoteDir
     *            遠程機的路徑
     * @param fileName
     *            文件名
     * @throws IOException
     * @throws IllegalStateException
     */
    public boolean deleteFile(String remoteDir, String fileName) throws IllegalStateException, IOException{
        ftpClient.changeWorkingDirectory(remoteDir);
        return ftpClient.deleteFile(fileName);
    }

    /**
     * 在FTP遠程機上,移動文件
     *
     * @param srcPath
     *            源數據
     * @param srcFileName
     *            源文件名
     * @param targetPath
     *            目標路路徑
     * @param targetFileName
     *            目標文件名
     * @throws IOException
     * @throws IllegalStateException
     */
    public void moveFile(String srcPath, String srcFileName, String targetPath, String targetFileName) throws IllegalStateException, IOException{
        ftpClient.changeWorkingDirectory(srcPath);

        if (!targetPath.endsWith("/")) {
            targetPath = targetPath + "/";
        }

        ftpClient.rename(srcFileName, targetPath + targetFileName);
    }

    /**
     *  在FTP遠程機上,更改文件名
     * @param regex
     * @param replacement
     * @param srcFileName
     * @throws IllegalStateException
     * @throws IOException
     */
    public boolean renameFile(String regex, String replacement, String srcFileName) throws IllegalStateException, IOException{
        String targetFileName = srcFileName.replaceAll(regex, replacement);
        return ftpClient.rename(srcFileName, targetFileName);
    }

    /**
     * 在遠程機,取得該目錄下的所有文件
     *
     * @param remoteDir
     *            遠程機目錄
     * @return 結果
     * @throws IOException
     * @throws IllegalStateException
     */
    public FTPFile[] getFileList(String remoteDir) throws IllegalStateException, IOException {
        ftpClient.changeWorkingDirectory(remoteDir);
        FTPFile[] result = ftpClient.listFiles();
        return result;
    }


    public static void main(String args[]){

        FtpClientHandler ftpClientUtils = new FtpClientHandler("192.168.1.100",21,"root","******");
        try {
            ftpClientUtils.connectFtpServer();
//            //下載文件
//            ftpClientUtils.download("/opt/sync","ctbInfo_2012.txt","E://data","ctbInfo_2014.txt");
            //上傳文件
            ftpClientUtils.upload("E://data","ctbInfo_2014.txt","/opt/sync","ctbInfo_2015.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                ftpClientUtils.closeConnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章