FTP测试工具类「建议收藏」

FTP测试工具类「建议收藏」因项目现场无法部署IDE工具联调FTP服务器,开发个简单的小工具,打成jar部署联调测。一下是该工具的源代码。packagecn.org.july.ftp;importorg.apache.commons.net.ftp.FTPClient;importorg.apache.commons.net.ftp.FTPFile;importorg.apache.commons.net….

大家好,又见面了,我是你们的朋友全栈君。

在进入正文前,先给大家分享一款比较好用的服务器连接工具
IIS7服务器管理工具是一款windows全系下用于连接并操控基于windows和linux系统的VPS、VNC、FTP等远程服务器、云服务器的管理工具。
界面简单明了,操作易上手,功能强大,支持批量导入服务器,并批量打开,多窗口化管理,除此之外,加载本地硬盘、硬盘映射、加载服务器的声音,远程声卡读取等功能也一应俱全,完全实现了各类场景使用,对于FTP连接界面,其中FTP文件的定时上传,定时下载(也可以说定时上传下载、定时备份)功能,对于经常使用FTP的小伙伴来说,也是非常适用的。
工具支持自动更新,压缩包只有7.62M,方便简洁,一步到位。
下载地址:IIS7服务器管理工具
简单的使用步骤可以看下面的截图,做了详细标注:
在这里插入图片描述
在这里插入图片描述

下面开始我们文章的内容

因项目现场无法部署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();
        }
    }
}

在这里插入图片描述
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/138773.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月6日 下午7:40
下一篇 2022年5月6日 下午8:00


相关推荐

  • x86为什么不叫x32_华为鲲鹏cpu是x86架构吗

    x86为什么不叫x32_华为鲲鹏cpu是x86架构吗整理了下网上的资料,归类了下,大似表述是这样的:IBM/PC兼容机,也就是Intel的i80x86指令架构,就简称了x86。x86并不是指32位环境,而是指80×86架构,这个架构目前有32位,64位

    2022年8月1日
    7
  • python urlopen()「建议收藏」

    首先调用urlopen需要导入urllib.request模块。urllib.request:urlopen():简单来说就是打开一个URL.url:来自百度百科urlopen的返回值,测试:可见返回值是http.client.HTTPResponsed对象。http.client.HTTPResponsed对象:详…

    2022年4月15日
    42
  • Spring AOP详解[通俗易懂]

    Spring AOP详解[通俗易懂]一、AOP1.1、AOP介绍1.1.1、什么是AOP?在软件业,AOP为AspectOrientedProgramming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从…

    2022年8月11日
    9
  • php和java区别_php和java的区别有哪些

    php和java区别_php和java的区别有哪些php 和 java 的区别是 PHP 是一种解释执行的脚本语言 语法和 C 语言类似 易学易用 非专业人员稍经学习也能使用 PHP 而 Java 要先编译成 Class 文件 然后在 Java 虚拟机上执行 Java 开发要熟悉 Java 语法以及一些核心的架构 java 开发和 PHP 开发有什么区别 Java 和 PHP 都是编程语言 大家知道它们最大的区别就是一个是静态语言一个是动态语言吧 没错 Java 是一种静态语言 PHP 是一种动

    2026年3月16日
    1
  • 旋转机械振动的基本特性分析图_旋转机械振动监测及故障诊断

    旋转机械振动的基本特性分析图_旋转机械振动监测及故障诊断旋转机械的主要功能是由旋转部件来完成的,转子是其最主要的部件。旋转机械发生故障的主要特征是机器伴有异常的振动和噪声,其振动信号从幅域、频域和时域反映了机器的故障信息。因此,了解旋转机械在故障状态下的振动机理,对于监测机器的运行状态和提高诊断故障的准确率都非常重要。一、转子振动的基本特性旋转机械的主要部件是转子,其结构型式虽然多种多样,但对一些简单的旋转机械来说,为分析和计算方便,一般都将转

    2022年8月31日
    9
  • layui 如何去dom_layui 弹出层

    layui 如何去dom_layui 弹出层这是一个可以重要也可以不重要的方法,重要的是,它的权利真的很大,尤其是在模块化加载layer时,你会发现你必须要用到它。它不仅可以配置一些诸如路径、加载的模块,甚至还可以决定整个弹层的默认参数。而说它不重要,是因为多数情况下,你会发现,你似乎不是那么十分需要它。但你真的需要认识一下这位伙计。如果您是采用seajs或者requirejs加载layer,你需要执行该方法来完成初始化的配置。比如:lay…

    2022年6月11日
    38

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号