java----ftp工具類


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");
    }

 

 

 

 



 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM