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();
            }
        }
    }

}


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