首页 > 解决方案 > java如何检查文件夹是否存在于同级子文件夹中?

问题描述

我的文件夹结构如下,我需要检查 AB1 文件夹中的文件并将其复制到 CD1 文件夹。

Root Folder
|___AB ------------------------>DD
    |__AB1 and AB2(folders)      |_AB1 and AB2
        |_CD1                       |__CD1 |__CD2

但它正在检查 AB1 和 AB2 文件夹中的 CD1,并且文件没有生成。

File file = new File("workspace");
List<File> abFolders = getDir(file); //level 1 folders
abFolders = new ArrayList<File>(abFolders);
List<File> cdFolders = getSubdirs(abFolders); //level 2 folders

//print
for (File file1 : abFolders) {
    for(File file2:cdFolders){
     //Here I need to check if CD folder is present in AB1 then it has to copy to CD1 and not to check for another CD1 folder in AB2 folder.
         System.out.println(file1.getName());
         System.out.println(file2.getName());
    }
    
}

private static List<File> getDir(File file) {
    List<File> subdirs = Arrays.asList(file.listFiles(new FileFilter() {
        public boolean accept(File f) {
            return f.isDirectory();
        }
    }));
    return subdirs;
}
static List<File> getSubdirs(List<File> subdirs) {
    List<File> deepSubdirs = new ArrayList<File>();
    for(File subdir : subdirs) {
        deepSubdirs.addAll(getDir(subdir)); 
    }
    //subdirs.addAll(deepSubdirs);
    return deepSubdirs;
}

标签: java

解决方案


使用集合,以便您对 abFolders 和 cdFolders 进行排序。首先导入库:

import java.util.Collections;

然后在进入循环之前执行 AB 文件夹的排序。

Collections.sort(abFolders);
for (File file1 : abFolders) {
    for(File file2:cdFolders){
     //Here I need to check if CD folder is present in AB1 then it has to copy to CD1 and not to check for another CD1 folder in AB2 folder.
         System.out.println(file1.getName());
         System.out.println(file2.getName());
    }
    
}

推荐阅读