FTP測試工具類

因項目現場無法部署IDE工具聯調FTP服務器,開發個簡單的小工具,打成jar部署聯調測。一下是該工具的源代碼。

package cn.org.july.ftp;

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

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

public class FtpTest {

    private static String address = "";
    private static int port = 21;
    private static String userName;
    private static String pwd;
    private static FTPClient ftpClient;
    private static String userDir = System.getProperty("user.dir");


    public static void init() {
        Scanner scan = new Scanner(System.in);
        System.out.println("please enter the FTP service address: (請輸入FTP服務地址:)");
        address = scan.nextLine();
        System.out.println("ftp address is ".concat(address));
        System.out.println("please enter the FTP service port:(請輸入FTP服務端口:)");
        port = Integer.valueOf(scan.nextLine());
        System.out.println("ftp port is ".concat(port + ""));
        System.out.println("please enter the FTP service user: (請輸入FTP服務用戶:)");
        userName = scan.nextLine();
        System.out.println("ftp user is ".concat(userName));
        System.out.println("please enter the FTP service pwd: (請輸入FTP服務用戶密碼:)");
        pwd = scan.nextLine();
        System.out.println("ftp pwd is ".concat(pwd));
    }

    public static void connect() {
        try {
            ftpClient = new FTPClient();
            ftpClient.setConnectTimeout(60000);
            ftpClient.connect(address, port);// 連接FTP服務器
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                if (ftpClient.login(userName, pwd)) {// 登陸FTP服務器
                    if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                            "OPTS UTF8", "ON"))) {// 開啓服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK).
                        ftpClient.setControlEncoding("UTF-8");
                    } else {
                        ftpClient.setControlEncoding("GBK");
                    }
                    ftpClient.enterLocalPassiveMode();// 設置被動模式
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 設置傳輸的模式,以二進制流的方式讀取
                    ftpClient.enterLocalPassiveMode();
                    System.out.println("FTP服務連接成功!");
                } else {
                    System.out.println("FTP服務用戶名或密碼錯誤!");
                    disConnection();
                }
            } else {
                System.out.println("連接到FTP服務失敗!");
                disConnection();
            }
        } catch (SocketException e) {
            e.printStackTrace();
            disConnection();
            System.out.println("FTP的IP地址可能錯誤,請正確配置。");
        } catch (IOException e) {
            e.printStackTrace();
            disConnection();
            System.out.println("FTP的端口錯誤,請正確配置。");
        }
    }


    /**
     * 關閉FTP服務鏈接
     *
     * @throws IOException
     */
    public static void disConnection() {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 獲取文件夾下的所有文件信息
     *
     * @param path 文件路徑
     */
    public static void getFTPDirectoryFiles(String path) {
        FTPFile[] files = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            files = ftpClient.listFiles();
            for (FTPFile file : files) {
                System.out.println(file.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("FTP讀取數據異常!");
        } finally {
            //關閉連接
            disConnection();
        }
    }

    /**
     * 獲取文件夾下的所有文件信息
     *
     * @param path 文件路徑
     */
    public static void getFTPFile(String path, String fileName) {
        InputStream in = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            FTPFile[] files = ftpClient.listFiles();
            if (files.length > 0) {
                in = ftpClient.retrieveFileStream(new String(fileName.getBytes(), "ISO-8859-1"));
            }
            writeToLocal("ftpFile".concat(File.separator).concat(System.currentTimeMillis() + "").concat(fileName), in);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("FTP讀取數據異常!");
        } finally {
            //關閉連接
            disConnection();
        }
    }

    /**
     * 將InputStream寫入本地文件
     *
     * @param destination 寫入本地目錄
     * @param input       輸入流
     * @throws IOException IOException
     */
    public static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        String downPath = userDir.concat(File.separator).concat(destination);
        File file = new File(downPath);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdir();
            }
            file.createNewFile();
        }
        FileOutputStream downloadFile = new FileOutputStream(downPath);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        input.close();
        downloadFile.close();
        System.out.println("文件下載路徑:" + downPath);
    }


    public static void operation() throws FileNotFoundException {
        System.out.println("1:下載操作。2:上傳操作。3:遍歷目錄下文件");
        Scanner scan = new Scanner(System.in);
        String exit = scan.nextLine();
        if ("1".equals(exit)) {
            System.out.println("ftp download path (下載路徑:)");
            String path = scan.nextLine();
            System.out.println("ftp download path is ".concat(path));
            System.out.println("ftp download fileName(下載文件名稱:) ");
            String fileName = scan.nextLine();
            System.out.println("ftp download fileName is ".concat(fileName));
            getFTPFile(path, fileName);
        } else if ("2".equals(exit)) {
            System.out.println("please enter the local file path(請輸入本地文件路徑E:/test.pdf)");
            String localPath = scan.nextLine();
            System.out.println("local file path is ".concat(localPath));
            System.out.println("please enter the ftp file path (請輸入ftp文件路徑)");
            String ftpPath = scan.nextLine();
            System.out.println("ftp path is ".concat(ftpPath));
            System.out.println("please enter ftp file name (請輸入ftp文件名稱)");
            String fileName = scan.nextLine();
            System.out.println("ftp file name is ".concat(fileName));
            boolean b = uploadFile(ftpPath, fileName, new FileInputStream(new File(localPath)));
            if (b) {
                System.out.println("file upload success");
            } else {
                System.out.println("file upload fail");
            }
        } else if ("3".equals(exit)) {
            System.out.println("please enter ftp path:(請輸入FTP文件路徑)");
            String path = scan.nextLine();
            getFTPDirectoryFiles(path);
        } else {
            System.out.println("操作類型錯誤。");
        }
    }


    /**
     * Description: 向FTP服務器上傳文件
     *
     * @param ftpPath  FTP服務器中文件所在路徑 格式: ftptest/aa
     * @param fileName ftp文件名稱
     * @param input    文件流
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadFile(String ftpPath,
                                     String fileName, InputStream input) {
        boolean success = false;
        try {
            int reply;
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                System.err.println("不存在");
                boolean makeDirectory = ftpClient.makeDirectory(ftpPath);
                boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(ftpPath);
                System.err.println(ftpPath + "創建:" + makeDirectory + ";切換:" + changeWorkingDirectory);
            } else {
                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;
    }

    public static void main(String[] args) {
        init();
        connect();
        try {
            operation();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

在這裏插入圖片描述
在這裏插入圖片描述

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