Java,仅列出目录中的子目录,而不是文件 [英] Java, List only subdirectories from a directory, not files

查看:121
本文介绍了Java,仅列出目录中的子目录,而不是文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如何仅从目录中列出子目录?



我想使用java.io.File功能,最好的方法是什么在Java中这样做?你可以使用文件类列出目录。

  File file = new File(/ path / to / directory); 
String [] directories = file.list(new FilenameFilter(){
@Override
public boolean accept(File current,String name){
return new File(current,name ).isDirectory();
}
});
System.out.println(Arrays.toString(directories));

更新



作者对这篇文章的评论想要一个更快的方式,在这里进行很好的讨论:
如何在Java中快速检索目录列表



基本上:


  1. 如果你控制文件结构,我会尽量避免这种情况。

  2. 在Java NIO.2中,你可以使用目录函数返回一个迭代器以允许更大的缩放。目录流类是一个可用于遍历目录中的条目的对象。


In Java, How do I list only subdirectories from a directory?

I'd like to use the java.io.File functionality, what is the best method in Java for doing this?

解决方案

You can use the File class to list the directories.

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

Update

Comment from the author on this post wanted a faster way, great discussion here: How to retrieve a list of directories QUICKLY in Java?

Basically:

  1. If you control the file structure, I would try to avoid getting into that situation.
  2. In Java NIO.2, you can use the directories function to return an iterator to allow for greater scaling. The directory stream class is an object that you can use to iterate over the entries in a directory.

这篇关于Java,仅列出目录中的子目录,而不是文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆