JavaFTP遞歸查詢指定目錄下的所有目錄和文件


  1. 需要在前端展示ftp服務器中的目錄結構,實現用戶對ftp目錄實時查詢和其他文件操作。
  2. 采用遞歸方式,用戶傳入目錄,遞歸查詢,按層級結構封裝,返回給前端,前端按層級展示給用戶。
  3. 依賴apache的commons-net3.6提供的ftp功能。
  4. 下列代碼可以直接當作一個spring-boot controller使用。
  5. 特別注意:遞歸式遍歷目錄,性能不高。我實踐發現,在目錄層級深、文件數量多時,遍歷耗時特別長。故建議僅在目錄深度和文件數量都有限(比如屈指可數)的場景下使用。
package com.projects.se1080.qrcode_auth.controller;

import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:Yjx
 * @description:
 * @date:2019/6/28 19:46
 */
@RestController
@RequestMapping("/ftp")
public class RecursionFtp {

    @Resource
    private FtpConfig ftpConfig;

    @ApiOperation("遞歸列出FTP目錄下的內容(包括文件和目錄)")
    @PostMapping("/recursionDir")
    public MyTree recursionDir(@RequestBody ListDirDTO dto) throws Exception {
        FTPClient ftp = this.initFtpClient();
        if (ftp.getReplyCode() > 0) {
            String directory = dto.getDirectory();
            ftp.changeWorkingDirectory(directory);
            FTPFile[] ftpFiles = ftp.listFiles();
            MyTree root = new MyTree(directory);
            if (ftpFiles.length > 0) {
                this.recursion(ftpFiles, ftp, root);
            }
            this.destroyFtpClient(ftp);
            return root;
        } else {
            return null;
        }
    }

    private MyTree recursion(FTPFile[] fileArr, FTPClient ftp, MyTree myTree) throws Exception {
        if (fileArr.length > 0) {
            for (FTPFile it : fileArr) {
                if (it.isDirectory()) {
                    ftp.changeWorkingDirectory(new String(it.getName().getBytes("utf-8"), "iso-8859-1"));
                    FTPFile[] ftpFiles = ftp.listFiles();
                    if (ftpFiles.length > 0) {
                        myTree.getChildren().add(this.recursion(ftpFiles, ftp, new MyTree(it.getName())));
                    } else {
                        myTree.getChildren().add(new MyTree(it.getName()));
                        ftp.changeToParentDirectory();  // 空目錄務必要返回上一級
                    }
                } else {
                    myTree.getChildren().add(new MyTree(it.getName()));
                }
            }
        }
        ftp.changeToParentDirectory();
        return myTree;
    }

    /**
     * 初始化ftpClient
     *
     * @return
     * @throws IOException
     */
    private FTPClient initFtpClient() throws IOException {
        FTPClient ftp = new FTPClient();
        ftp.connect(this.ftpConfig.getIp(), this.ftpConfig.getPort());
        ftp.login(this.ftpConfig.getUsername(), this.ftpConfig.getPassword());
        ftp.setBufferSize(this.ftpConfig.getBufferSize());
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftp.changeWorkingDirectory(this.ftpConfig.getBaseDir());  //對於某些ftp認證模式,需要配置用戶的ftp根目錄
        return ftp;
    }

    /**
     * 銷毀ftpClient
     *
     * @param ftpClient
     * @throws IOException
     */
    private void destroyFtpClient(FTPClient ftpClient) throws IOException {
        ftpClient.logout();
        ftpClient.disconnect();
    }

}

/**
 * ftp服務器相關配置
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "ftp")
class FtpConfig {

    private String ip = "192.168.1.10";

    private int port = 21;

    private String username = "myFtp";

    private String password = "xxxxxx";

    private String baseDir = "/";

    private int bufferSize = 1024 * 1024 * 4;

}

@Data
class MyTree {

    private String name;

    private List<MyTree> children;

    public MyTree() {
    }

    public MyTree(String name) {
        this.name = name;
        this.children = new ArrayList<>();
    }

    public MyTree(String name, List<MyTree> children) {
        this.name = name;
        this.children = children;
    }
}



免責聲明!

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



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