Java nio,获取某些文件夹

时间:2016-07-08 14:24:03

标签: java nio

我怎样才能获得某个文件夹的所有子文件夹?我会使用JDK 8和nio。

picture

例如,对于文件夹" Designs.ipj"方法应该返回{"工作区","图书馆1"}

提前谢谢!

2 个答案:

答案 0 :(得分:7)

    List<Path> subfolder = Files.walk(folderPath, 1)
            .filter(Files::isDirectory)
            .collect(Collectors.toList());

它将包含folderPath和深度为1的所有子文件夹。如果只需要子文件夹,只需添加:

subfolders.remove(0);

答案 1 :(得分:0)

您必须阅读文件夹中的所有项目并过滤掉目录,并根据需要多次重复此过程。

为此,您可以使用listFiles()

In [157]: # Setup dataframes A and B with rows 0, 4 in A having matches from B
     ...: A_arr = np.random.randint(0,2,(10,14))
     ...: B_arr = np.random.randint(0,2,(7,10))
     ...: 
     ...: B_arr[2] = A_arr[4,1:11]
     ...: B_arr[4] = A_arr[4,1:11]
     ...: B_arr[5] = A_arr[0,1:11]
     ...: 
     ...: A = pd.DataFrame(A_arr)
     ...: B = pd.DataFrame(B_arr)
     ...: 

In [158]: S = 2**np.arange(10)
     ...: A_ID = np.dot(A[range(1,11)],S)
     ...: B_ID = np.dot(B,S)
     ...: out_row_idx = np.where(np.in1d(A_ID,B_ID))[0]
     ...: 

In [159]: out_row_idx
Out[159]: array([0, 4])

Getting the filenames of all files in a folder 一个简单的递归函数也可以工作,只要确保对无限循环保持警惕。

但是我更偏向于DirectoryStream。它允许您创建一个过滤器,以便您只添加符合您规格的项目。

File folder = new File("your/path");
Stack<File> stack = new Stack<File>();
Stack<File> folders = new Stack<File>();

stack.push(folder);
while(!stack.isEmpty())
    {
        File child = stack.pop();
        File[] listFiles = child.listFiles();
        folders.push(child);

        for(File file : listFiles)
        {
            if(file.isDirectory())
            {
                stack.push(file);
            }
        }            
    }