cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java Source code

Java tutorial

Introduction

Here is the source code for cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.zhuqi.mavenssh.web.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * FTP
 *
 * @author zhuqi259
 * @version 1.0
 */
public class FTPClientTemplate {
    //---------------------------------------------------------------------
    // Instance data
    //---------------------------------------------------------------------
    /**
     * logger
     */
    protected final Logger log = Logger.getLogger(getClass());
    private ThreadLocal<FTPClient> ftpClientThreadLocal = new ThreadLocal<>();

    private String host;
    private int port;
    private String username;
    private String password;

    private boolean binaryTransfer = true;
    private boolean passiveMode = true;
    private String encoding = "UTF-8";
    private int clientTimeout = 1000 * 30;

    public FTPClientTemplate() {
    }

    public FTPClientTemplate(String host, int port, String username, String password) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isBinaryTransfer() {
        return binaryTransfer;
    }

    public void setBinaryTransfer(boolean binaryTransfer) {
        this.binaryTransfer = binaryTransfer;
    }

    public boolean isPassiveMode() {
        return passiveMode;
    }

    public void setPassiveMode(boolean passiveMode) {
        this.passiveMode = passiveMode;
    }

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public int getClientTimeout() {
        return clientTimeout;
    }

    public void setClientTimeout(int clientTimeout) {
        this.clientTimeout = clientTimeout;
    }

    //---------------------------------------------------------------------
    // private method
    //---------------------------------------------------------------------
    /**
     * FTPClient
     *
     * @throws Exception
     */
    private FTPClient getFTPClient() throws Exception {
        if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {
            return ftpClientThreadLocal.get();
        } else {
            FTPClient ftpClient = new FTPClient(); //FtpClient
            ftpClient.setControlEncoding(encoding); //

            connect(ftpClient); //ftp?

            //passive?
            if (passiveMode) {
                ftpClient.enterLocalPassiveMode();
            }
            setFileType(ftpClient); //

            try {
                ftpClient.setSoTimeout(clientTimeout);
            } catch (SocketException e) {
                throw new Exception("Set timeout error.", e);
            }
            ftpClientThreadLocal.set(ftpClient);
            return ftpClient;
        }
    }

    /**
     * 
     *
     * @throws Exception
     * @throws IOException
     */
    private void setFileType(FTPClient ftpClient) throws Exception {
        try {
            if (binaryTransfer) {
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            } else {
                ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
            }
        } catch (IOException e) {
            throw new Exception("Could not to set file type.", e);
        }
    }

    /**
     * ftp?
     *
     * @param ftpClient
     * @return ?true?false
     * @throws Exception
     */
    private boolean connect(FTPClient ftpClient) throws Exception {
        try {
            ftpClient.connect(host, port);

            // ?????
            int reply = ftpClient.getReplyCode();

            if (FTPReply.isPositiveCompletion(reply)) {
                //ftp?
                if (ftpClient.login(username, password)) {
                    setFileType(ftpClient);
                    return true;
                }
            } else {
                ftpClient.disconnect();
                throw new Exception("FTP server refused connection.");
            }
        } catch (IOException e) {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect(); //
                } catch (IOException e1) {
                    throw new Exception("Could not disconnect from server.", e1);
                }

            }
            throw new Exception("Could not connect to server.", e);
        }
        return false;
    }

    //---------------------------------------------------------------------
    // public method
    //---------------------------------------------------------------------
    /**
     * ftp
     *
     * @throws Exception
     */
    public void disconnect() throws Exception {
        try {
            FTPClient ftpClient = getFTPClient();
            ftpClient.logout();
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
                ftpClient = null;
            }
        } catch (IOException e) {
            throw new Exception("Could not disconnect from server.", e);
        }
    }

    public boolean mkdir(String pathname) throws Exception {
        return mkdir(pathname, null);
    }

    /**
     * ftp???
     *
     * ??
     *
     * @param pathname
     * @param workingDirectory
     * @return
     * @throws Exception
     */
    public boolean mkdir(String pathname, String workingDirectory) throws Exception {
        return mkdir(pathname, workingDirectory, true);
    }

    /**
     * ftp???
     *
     * @param pathname
     * @param workingDirectory
     * @param autoClose ??
     * @return
     * @throws Exception
     */
    public boolean mkdir(String pathname, String workingDirectory, boolean autoClose) throws Exception {
        try {
            getFTPClient().changeWorkingDirectory(workingDirectory);
            return getFTPClient().makeDirectory(pathname);
        } catch (IOException e) {
            throw new Exception("Could not mkdir.", e);
        } finally {
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    /**
     * 
     *
     * @param remoteAbsoluteFile ??()
     * @param localAbsoluteFile ??()
     * @return ?truefalse
     * @throws Exception
     */
    public boolean put(String remoteAbsoluteFile, String localAbsoluteFile) throws Exception {
        return put(remoteAbsoluteFile, localAbsoluteFile, true);
    }

    /**
     * 
     *
     * @param remoteAbsoluteFile ??()
     * @param localAbsoluteFile ??()
     * @param autoClose ??
     * @return ?truefalse
     * @throws Exception
     */
    public boolean put(String remoteAbsoluteFile, String localAbsoluteFile, boolean autoClose) throws Exception {
        InputStream input = null;
        try {
            // ?
            input = new FileInputStream(localAbsoluteFile);
            getFTPClient().storeFile(remoteAbsoluteFile, input);
            log.debug("put " + localAbsoluteFile);
            return true;
        } catch (FileNotFoundException e) {
            throw new Exception("local file not found.", e);
        } catch (IOException e) {
            throw new Exception("Could not put file to server.", e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                throw new Exception("Couldn't close FileInputStream.", e);
            }
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    /**
     *  ???
     *
     * @param remoteAbsoluteFile ??()
     * @param input
     * @return ?truefalse
     * @throws Exception
     */
    public boolean put(String remoteAbsoluteFile, InputStream input) throws Exception {
        return put(remoteAbsoluteFile, input, true);
    }

    /**
     *  ???
     *
     * @param remoteAbsoluteFile ??()
     * @param input
     * @param autoClose ??
     * @return ?truefalse
     * @throws Exception
     */
    public boolean put(String remoteAbsoluteFile, InputStream input, boolean autoClose) throws Exception {
        try {
            // ?
            getFTPClient().storeFile(remoteAbsoluteFile, input);
            return true;
        } catch (FileNotFoundException e) {
            throw new Exception("local file not found.", e);
        } catch (IOException e) {
            throw new Exception("Could not put file to server.", e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                throw new Exception("Couldn't close FileInputStream.", e);
            }
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    /**
     * 
     *
     * @param remoteAbsoluteFile ??()
     * @param localAbsoluteFile ??()
     * @return ?truefalse
     * @throws Exception
     */
    public boolean get(String remoteAbsoluteFile, String localAbsoluteFile) throws Exception {
        return get(remoteAbsoluteFile, localAbsoluteFile, true);
    }

    /**
     * 
     *
     * @param remoteAbsoluteFile ??()
     * @param localAbsoluteFile ??()
     * @param autoClose ??
     *
     * @return ?truefalse
     * @throws Exception
     */
    public boolean get(String remoteAbsoluteFile, String localAbsoluteFile, boolean autoClose) throws Exception {
        OutputStream output = null;
        try {
            output = new FileOutputStream(localAbsoluteFile);
            return get(remoteAbsoluteFile, output, autoClose);
        } catch (FileNotFoundException e) {
            throw new Exception("local file not found.", e);
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                throw new Exception("Couldn't close FileOutputStream.", e);
            }
        }
    }

    /**
     * ? ???
     *
     * @param remoteAbsoluteFile
     * @param output
     * @return
     * @throws Exception
     */
    public boolean get(String remoteAbsoluteFile, OutputStream output) throws Exception {
        return get(remoteAbsoluteFile, output, true);
    }

    /**
     * ? ???
     *
     * @param remoteAbsoluteFile
     * @param output
     * @param autoClose
     * @return
     * @throws Exception
     */
    public boolean get(String remoteAbsoluteFile, OutputStream output, boolean autoClose) throws Exception {
        try {
            FTPClient ftpClient = getFTPClient();
            // ?
            return ftpClient.retrieveFile(remoteAbsoluteFile, output);
        } catch (IOException e) {
            throw new Exception("Couldn't get file from server.", e);
        } finally {
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    /**
     * ftp? ?
     *
     * @param delFile
     * @return
     * @throws Exception
     */
    public boolean delete(String delFile) throws Exception {
        return delete(delFile, true);
    }

    /**
     * ftp?
     *
     * @param delFile
     * @param autoClose ??
     *
     * @return
     * @throws Exception
     */
    public boolean delete(String delFile, boolean autoClose) throws Exception {
        try {
            getFTPClient().deleteFile(delFile);
            return true;
        } catch (IOException e) {
            throw new Exception("Couldn't delete file from server.", e);
        } finally {
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    /**
     * ? ?
     *
     * @param delFiles
     * @return
     * @throws Exception
     */
    public boolean delete(String[] delFiles) throws Exception {
        return delete(delFiles, true);
    }

    /**
     * ?
     *
     * @param delFiles
     * @param autoClose ??
     *
     * @return
     * @throws Exception
     */
    public boolean delete(String[] delFiles, boolean autoClose) throws Exception {
        try {
            FTPClient ftpClient = getFTPClient();
            for (String s : delFiles) {
                ftpClient.deleteFile(s);
            }
            return true;
        } catch (IOException e) {
            throw new Exception("Couldn't delete file from server.", e);
        } finally {
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    /**
     * 
     *
     * @return ???0
     * @throws Exception
     */
    public String[] listNames() throws Exception {
        return listNames(null, true);
    }

    public String[] listNames(boolean autoClose) throws Exception {
        return listNames(null, autoClose);
    }

    /**
     * 
     *
     * @param remotePath ??
     * @param autoClose ??
     *
     * @return ???0
     * @throws Exception
     */
    public String[] listNames(String remotePath, boolean autoClose) throws Exception {
        try {
            String[] listNames = getFTPClient().listNames(remotePath);
            return listNames;
        } catch (IOException e) {
            throw new Exception("", e);
        } finally {
            if (autoClose) {
                disconnect(); //
            }
        }
    }

    public static void main(String[] args) throws Exception, InterruptedException {
        FTPClientTemplate ftp = new FTPClientTemplate();
        ftp.setHost("192.168.0.111");
        ftp.setPort(21);
        ftp.setUsername("zl123456");
        ftp.setPassword("p123456");
        ftp.setBinaryTransfer(true);
        ftp.setPassiveMode(false);
        ftp.setEncoding("utf-8");

        //boolean ret = ftp.put("/group/tbdev/query/user-upload/12345678910.txt", "D:/099_temp/query/12345.txt");
        //System.out.println(ret);
        OutputStream output = null;
        output = new FileOutputStream("C:/1.jpg");
        ftp.get("Chrysanthemum.jpg", output);
        output.close();

        ftp.put("222.jpg", "C:/1.jpg");
        ftp.mkdir("data");
        ftp.mkdir("111", "data");
        //ftp.disconnect();
        //ftp.mkdir("user-upload1");
        //ftp.disconnect();
        //String[] aa = {"/group/tbdev/query/user-upload/123.txt", "/group/tbdev/query/user-upload/SMTrace.txt"};
        //ftp.delete(aa);
    }
}