FTPClient listFiles方法正在返回目录。我该如何过滤?

时间:2019-04-09 11:06:23

标签: java ftp-client

您可以看到FTPClient库具有FTPFileFilters类,该类提供了过滤DIRECTORIES,NON_NULL和ALL的选项

public class FTPFileFilters {
    /**
     * Accepts all FTPFile entries, including null.
     */
    public static final FTPFileFilter ALL = new FTPFileFilter() {
        @Override
        public boolean accept(FTPFile file) {
            return true;
        }
    };

    /**
     * Accepts all non-null FTPFile entries.
     */
    public static final FTPFileFilter NON_NULL = new FTPFileFilter() {
        @Override
        public boolean accept(FTPFile file) {
            return file != null;
        }
    };

    /**
     * Accepts all (non-null) FTPFile directory entries.
     */
    public static final FTPFileFilter DIRECTORIES = new FTPFileFilter() {
        @Override
        public boolean accept(FTPFile file) {
            return file != null && file.isDirectory();
        }
    };

}

问题是,我正在尝试下载文件和THEN目录的列表,以便可以以不同的方式处理它们:

从我的Connection.java:

// Download FTPFile[] of files and FTPFile[] of directories
// and give them to FileData for parsing and storage
public void downloadDirectory(String directory) {

    try {

        client.setFileType(FTP.BINARY_FILE_TYPE);

        // Copy the files into the FileData list. If directory null, its assumed to be ftp user root Todo really?
        FileData.getInstance().loadDirectoryContents(
                client.listFiles(directory /*, !FTPFileFilters.DIRECTORIES   Todo doesnt work*/),
                client.listDirectories());

    } catch (IOException e) {// Handle Todo

    }
}

从我的FileData.java:

public void loadDirectoryContents(FTPFile[] ftpFiles, FTPFile[] ftpDirectories){

        removeAllFiles();   // Clear remoteFiles list


        // Get
        for(int i =0; i< ftpFiles.length; i++){

            addRemoteFile(new RemoteFile(
                    ftpFiles[i].getName(),
                    ftpFiles[i].getLink(),
                    DateTimeManagement.toLocalDateTime(ftpFiles[i].getTimestamp()),
                    null,
                    false));
        }
        for(int i =0; i< ftpDirectories.length; i++){

            addRemoteFile(new RemoteFile(
                    "./" + ftpDirectories[i].getName(),
                    ftpDirectories[i].getLink(),
                    DateTimeManagement.toLocalDateTime(ftpDirectories[i].getTimestamp()),
                    null,
                    true));
        }

    }

最后,我得到一个包含文件和目录的列表,再加上目录。 我不明白为什么FTPClient提供listDirectories方法...和允许您仅获取目录的筛选器。这是多余的,无法只获取文件。所以问题是,仅获取文件的秘密是什么?

1 个答案:

答案 0 :(得分:1)

要仅过滤文件,可以使用:

  FTPFileFilter filter = new FTPFileFilter() {

         @Override
         public boolean accept(FTPFile ftpFile) {
         return ftpFile.isFile();
        }
  };

类似地,使用ftpFile.isDirectory();过滤目录。