java----ftp工具类

介绍一个     ftp客户端工具:iis7服务器管理工具

IIs7服务器管理工具可以批量管理ftp站点,同时具备定时上传下载的功能。作为服务器集成管理器,它最优秀的功能就是批量管理windows与linux系统服务器、vps。能极大的提高站长及服务器运维人员工作效率。同时iis7服务器管理工具还是vnc客户端,服务器真正实现了一站式管理,可谓是非常方便。下载地址http://yczm.iis7.com/?tscc

iis7服务器管理工具

 


 

此文章总结ftp的基本的上传下载,同步操作,代码均已测试,可以使用

question:中文的文档不能上传下载,注意编码问题

参考另一篇ftp文章: https://www.cnblogs.com/cbpm-wuhq/p/12054239.html

注意:上传下载的时的编码设置

一:环境准备

maven环境添加  commons-net,log4j


 <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
 最后springboot可能已经内置导入了
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
     <optional>true</optional>
</dependency>
 

二:编写配置的实体类,已经全局配置获取

1.application.yml配置实体类

#公共配置
server:
    address: 127.0.0.1
    port: 80
    tomcat:
      uri-encoding: UTF-8

#ftp配置 ftpserver: ipAddr:
172.20.0.101 port: 21 userName: ftpuser pwd: ftpuser path: /

 2.java实体类及配置获取
package com.kexin.admin.entity.ftp;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Description:ftp链接常量
 * @Author: 巫恒强
 * @Date: 2019/12/6 9:40
 */
@Component
@ConfigurationProperties(prefix = "ftpserver")
public class Ftp {
    private String ipAddr;//ip地址

    private Integer port;//端口号

    private String userName;//用户名

    private String pwd;//密码

    private String path;//aaa路径

    public String getIpAddr() {
        return ipAddr;
    }

    public void setIpAddr(String ipAddr) {
        this.ipAddr = ipAddr;
    }

    public Integer getPort() {
        return port;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

 


 3.导入到使用的地方
    @Value("${ftpserver.ipAddr}")
    private String ipAddr;


    @Autowired
    Ftp ftp;

 

三:ftpUtil类编写

 


package com.kexin.common.util;

import com.kexin.admin.entity.ftp.Ftp;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;

public class FtpUtil {

    private static Logger logger = Logger.getLogger(FtpUtil.class);

    private static FTPClient ftp;

    /**
     * 获取ftp连接
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static boolean connectFtp(Ftp f) throws Exception {
        ftp = new FTPClient();
        boolean flag = false;
        int reply;
        if (f.getPort() == null) {
            ftp.connect(f.getIpAddr(), 21);
        } else {
            ftp.connect(f.getIpAddr(), f.getPort());
        }
        ftp.login(f.getUserName(), f.getPwd());
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return flag;
        }
        ftp.changeWorkingDirectory(f.getPath());
        flag = true;
        return flag;
    }

    /**
     * 关闭ftp连接
     */
    public static void closeFtp() {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ftp上传文件
     *
     * @param f
     * @throws Exception
     */
    public static void upload(File f) throws Exception {
        ftp.setControlEncoding("GBK");
        if (f.isDirectory()) {
            ftp.makeDirectory(f.getName());
            ftp.changeWorkingDirectory(f.getName());

//            ftp.setControlEncoding("utf-8");
            String[] files = f.list();
            for (String fstr : files) {
                File file1 = new File(f.getPath() + "/" + fstr);
                if (file1.isDirectory()) {
                    upload(file1);
                    ftp.changeToParentDirectory();
                } else {
                    File file2 = new File(f.getPath() + "/" + fstr);
                    FileInputStream input = new FileInputStream(file2);
                    ftp.storeFile(file2.getName(), input);
                    input.close();
                }
            }
        } else {
            File file2 = new File(f.getPath());
            FileInputStream input = new FileInputStream(file2);
            ftp.storeFile(file2.getName(), input);
            input.close();
        }
    }

    /**
     * 下载链接配置
     * 本地与,远程地址同步,将所有文件都下载到本地
     * @param f
     * @param localBaseDir  本地目录
     * @param remoteBaseDir 远程目录
     * @throws Exception
     */
    public static void startDown(Ftp f, String localBaseDir, String remoteBaseDir) throws Exception {
        if (FtpUtil.connectFtp(f)) {

            try {
                FTPFile[] files = null;
                boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);
                if (changedir) {
                    ftp.setControlEncoding("GBK");
//                    ftp.setControlEncoding("utf-8");
                    files = ftp.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        try {
                            downloadFile(files[i], localBaseDir, remoteBaseDir);
                        } catch (Exception e) {
                            logger.error(e);
                            logger.error("<" + files[i].getName() + ">下载失败");
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e);
                logger.error("下载过程中出现异常");
            }
        } else {
            logger.error("链接失败!");
        }

    }


    /**
     * 下载FTP文件
     * 当你需要下载FTP文件的时候,调用此方法
     * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载
     *
     * @param ftpFile
     * @param relativeLocalPath
     * @param relativeRemotePath
     */
    private static void downloadFile(FTPFile ftpFile, String relativeLocalPath, String relativeRemotePath) {
        if (ftpFile.isFile()) {
            if (ftpFile.getName().indexOf("?") == -1) {
                OutputStream outputStream = null;
                try {
                    File locaFile = new File(relativeLocalPath + ftpFile.getName());
                    //判断文件是否存在,存在则返回
                    if (locaFile.exists()) {
                        return;
                    } else {
                        outputStream = new FileOutputStream(relativeLocalPath + ftpFile.getName());
                        ftp.setControlEncoding("GBK");
                        ftp.retrieveFile(ftpFile.getName(), outputStream);
                        outputStream.flush();
                        outputStream.close();
                    }
                } catch (Exception e) {
                    logger.error(e);
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        logger.error("输出文件流异常");
                    }
                }
            }
        } else {
            String newlocalRelatePath = relativeLocalPath + ftpFile.getName();
            String newRemote = new String(relativeRemotePath + ftpFile.getName().toString());
            File fl = new File(newlocalRelatePath);
            if (!fl.exists()) {
                fl.mkdirs();
            }
            try {
                newlocalRelatePath = newlocalRelatePath + '/';
                newRemote = newRemote + "/";
                String currentWorkDir = ftpFile.getName().toString();
                boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);
                if (changedir) {
                    FTPFile[] files = null;
                    files = ftp.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        downloadFile(files[i], newlocalRelatePath, newRemote);
                    }
                }
                if (changedir) {
                    ftp.changeToParentDirectory();
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }
}

三:main方法测试,这里用main方法测试就不用@Autowired导入的数据

 

    public static void main(String[] args) throws Exception {


        Ftp f = new Ftp();
        f.setIpAddr("172.20.0.101");
        f.setUserName("ftpuser");
        f.setPwd("ftpuser");

        System.out.println(f);
//        FtpUtil.connectFtp(f);

//        File file = new File("D:/text1.txt");
//        File file = new File("D:/filesUpload");


//        File file = new File("D:/新建文本文档.txt");

//        FtpUtil.upload(file);//把文件上传在ftp上

        //整个目录的文件都下载 //下载ftp文件测试
        /**
         * 整个文件的目录都下载
         */
//        FtpUtil.startDown(f, "d:/files/", "/");

        /**
         * 下载单个文件
         */

        FTPFile ftpFile = new FTPFile();
/*        文件type设置为0
        *
         * type:
         * 文件:0,文件夹:1,符号链接:2,不存在:3*/

        ftpFile.setType(0);
        ftpFile.setRawListing("/中文下载测试.txt");
//        ftpFile.setName("text.txt");
        ftpFile.setName("中文下载测试.txt");
        FtpUtil.downloadFile(ftpFile, "d:/files/", "/");//下载文件
        System.out.println("finished");
    }

 

 

 

 



 



 posted on 2019-12-06 14:23  wu小强  阅读(2964)  评论(0编辑  收藏  举报