欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ftp客户端往服务端上传文件

程序员文章站 2024-03-22 18:51:52
...
基于commons-net实现ftp客户端创建文件夹、文件上传、下载功能

1、导入commons-net maven坐标

<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

2、为了方便使用,已经封装成了一个工具FtpClientUtil

package com.chen.ftpclient.demo;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.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.ConnectException;
/**
 * @description: FtpClientUtil
 * @date: 2019/6/12 17:27
 * @author: https://blog.csdn.net/chen_2890
 */
public class FtpClientUtil {
    /**
     * ftp服务器地址
     */
    private String server;
    /**
     * 端口
     */
    private int port;
    /**
     * 用户名
     */
    private String username;
    /**
     *
     */
    private String password;

    public FtpClientUtil() {
        server = "192.168.3.110";
        port = 1111;
        username = "uftp";
        password = "uftp222";
    }
    public FtpClientUtil(String server, int port, String username,
                         String password) {
        this.server = server;
        this.port = port;
        this.username = username;
        this.password = password;
    }
    /**
     * @param remoteFilePath 远程文件路径,是相对路径
     * @param localFilePath 本地文件路径,是绝对路径
     * @return void
     * @description 上传文件
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:16
     * @version V1.0
     */
    public void upload(String remoteFilePath, String localFilePath) {
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
            //连接ftp服务器
            connect(ftp);
            //设置属性
            setProperty(ftp);
            //在ftp服务中创建文件夹,如果存在则不创建
            String[] fileNames = remoteFilePath.split("/");
            for (Integer i = 0; i < fileNames.length - 1; i++) {
                ftp.makeDirectory(fileNames[i]);
                ftp.changeWorkingDirectory(fileNames[i]);
            }
            //上传文件
            if(!existFile(ftp,remoteFilePath)){
                upload(ftp,fileNames[fileNames.length - 1], localFilePath);
            }else{
                System.out.println("[存在]:"+remoteFilePath);
            }
            //退出
            logout(ftp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                }
            }
        }
    }
    /**
     * @param remoteFilePath 远程文件路径,是相对路径
     * @param localFilePath   本地文件路径,是绝对路径
     * @return void
     * @description 文件下载
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:16
     * @version V1.0
     */
    public void download(String remoteFilePath, String localFilePath) {
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
            //连接ftp服务器
            connect(ftp);
            //设置属性
            setProperty(ftp);
            //下载文件
            download(ftp, remoteFilePath, localFilePath);
            //退出
            logout(ftp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                }
            }
        }
    }
    /**
     * @param remotePathName 远程文件夹名称,不支持多层级目录的创建
     * @return void
     * @description 创建文件夹
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:19
     * @version V1.0
     */
    public void mkdir(String remotePathName) {
        
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
            //连接ftp服务器
            connect(ftp);
            //设置属性
            setProperty(ftp);
            //创建文件夹
            mkdir(ftp, remotePathName);
            //退出
            logout(ftp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                }
            }
        }
    }
    /**
     * @param ftp
     * @param remotePathName
     * @return void
     * @description 创建文件夹
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:20
     * @version V1.0
     */
    private void mkdir(FTPClient ftp, String remotePathName) throws Exception {
        ftp.makeDirectory(remotePathName);
    }
    /**
     * @description 下载
     * @param ftp
     * @param remoteFilePath
     * @param localFilePath
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:21
     * @version V1.0
     */
    private void download(FTPClient ftp, String remoteFilePath,
                          String localFilePath) throws Exception {
        OutputStream output = new FileOutputStream(localFilePath);
        ftp.retrieveFile(remoteFilePath, output);
        output.close();
    }
    /**
     * @description 设置属性
     * @param ftp
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:22
     * @version V1.0
     */
    private void setProperty(FTPClient ftp) throws Exception {
        ftp.enterLocalPassiveMode();
        //二进制传输,默认为ASCII
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
    }
    /**
     * @description 退出登录
     * @param ftp
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:22
     * @version V1.0
     */
    private void logout(FTPClient ftp) throws Exception {
        ftp.noop();
        ftp.logout();
    }
    /**
     * @description 文件上传
     * @param ftp
     * @param remoteFilePath
     * @param localFilePath
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:22
     * @version V1.0
     */
    private void upload(FTPClient ftp, String remoteFilePath,
                        String localFilePath) throws Exception {
        //上传
        InputStream input;
        
        input = new FileInputStream(localFilePath);

        ftp.storeFile(remoteFilePath, input);

        input.close();
        
    }
    /**
     * @description ftp连接
     * @param ftp
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:23
     * @version V1.0
     */
    private void connect(FTPClient ftp) throws Exception {
        //连接服务器
        ftp.connect(server, port);
        int reply = ftp.getReplyCode();
        //是否连接成功
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new ConnectException(server + " 服务器拒绝连接");
        }
        //登陆
        if (!ftp.login(username, password)) {
            throw new ConnectException("用户名或密码错误");
        }
    }
    /**
     * @description 判断ftp服务器文件是否存在
     * @param ftp
     * @param path
     * @return boolean
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:23
     * @version V1.0
     */
    public static boolean existFile(FTPClient ftp, String path) {
        boolean flag = false;
        try {
            ftp.enterLocalPassiveMode();
            FTPFile[] ftpFileArr = ftp.listFiles(path);
            if (ftpFileArr.length > 0) {
                flag = true;
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println(ioe.getMessage());
        }

        return flag;
    }
}

3、测试用例

package com.chen.ftpclient.demo;

/**
 * @description: FtpTest
 * @date: 2019/6/12 17:28
 * @author: https://blog.csdn.net/chen_2890
 */
public class FtpTest {

    /**
     * @description 测试main方法
     * @param args
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:27
     * @version V1.0
     */
    public static void main(String[] args) {
        //上传文件
        upload();
        //下载文件
        //download();
        //创建文件夹
        //mkdir();
    }
    /**
     * @description 测试创建文件夹功能
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:26
     * @version V1.0
     */
    private static void mkdir() {
        FtpClientUtil clientUtil = new FtpClientUtil();
        clientUtil.mkdir("test");
    }
    /**
     * @description 测试文件下载功能
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:26
     * @version V1.0
     */
    private static void download() {
        String remoteFilePath = "/C6666666/2019-06-12/20190612013246.jpg";
        String localFilePath = "F:\\test\\20190612013246.jpg";
        FtpClientUtil clientUtil = new FtpClientUtil();
        clientUtil.download(remoteFilePath, localFilePath);
    }
    /**
     * @description 测试文件上传功能
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/6/12 17:27
     * @version V1.0
     */
    private static void upload() {
        String remoteFilePath = "/C6666666/2019-06-12/20190612013246.jpg";
        String localFilePath = "F:\\test\\20190612013246.jpg";
        FtpClientUtil clientUtil = new FtpClientUtil();
        clientUtil.upload(remoteFilePath, localFilePath);
    }
}

要是还有不太明白的地方请留言,评论必回
要是对我的文章感兴趣的话,关注一下吧,谢谢!

上一篇:Linux基本命令

下一篇:Linux下如何部署jar包并后台运行?