java列出指定目录下的所有文件

上大王 分享于 昨天 2622阅 0人收藏此代码, 我要收藏

这段Java代码用于列出指定文件夹(目录)下的所有文件

File dir = new File("directoryName");
  String[] children = dir.list();
  if (children == null) {
      // Either dir does not exist or is not a directory
  } else {
      for (int i=0; i < children.length; i++) {
          // Get filename of file or directory
          String filename = children[i];
      }
  }
 
  // It is also possible to filter the list of returned files.
  // This example does not return any files that start with `.'.
  FilenameFilter filter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
          return !name.startsWith(".");
      }
  };
  children = dir.list(filter);
 
  // The list of files can also be retrieved as File objects
  File[] files = dir.listFiles();
 
  // This filter only returns directories
  // http://www.sharejs.com/codes/
  FileFilter fileFilter = new FileFilter() {
      public boolean accept(File file) {
          return file.isDirectory();
      }
  };
  files = dir.listFiles(fileFilter);
//该代码片段来自于: http://www.sharejs.com/codes/java/8841

标签:
  • 文件列表
  • 目录列表
  • Java