列出文件和目录

  1. File dir = new File(“directoryName”);
  2.   String[] children = dir.list();
  3.   if (children == null) {
  4.       // Either dir does not exist or is not a directory  
  5.   } else {
  6.       for (int i=0; i < children.length; i++) {
  7.           // Get filename of file or directory  
  8.           String filename = children[i];
  9.       }
  10.   }
  11.   // It is also possible to filter the list of returned files.  
  12.   // This example does not return any files that start with `.’.  
  13.   FilenameFilter filter = new FilenameFilter() {
  14.       public boolean accept(File dir, String name) {
  15.           return !name.startsWith(“.”);
  16.       }
  17.   };
  18.   children = dir.list(filter);
  19.   // The list of files can also be retrieved as File objects  
  20.   File[] files = dir.listFiles();
  21.   // This filter only returns directories  
  22.   FileFilter fileFilter = new FileFilter() {
  23.       public boolean accept(File file) {
  24.           return file.isDirectory();
  25.       }
  26.   };
  27.   files = dir.listFiles(fileFilter);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.