列出文件夹中的所有文件以及子文件夹

可能重复:
用Javarecursion列出目录中的所有文件

我怎样才能返回一个文件数组,其中包括文件夹上的所有文件,也是我的方法只是文件夹的子文件夹,它不包括子文件夹。

public File[] listf(String directoryName) { // .............list file File directory = new File(directoryName); // get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList) { if (file.isFile()) { System.out.println(file.getAbsolutePath()); } else if (file.isDirectory()) { listf(file.getAbsolutePath()); } } System.out.println(fList); return fList; } 

使用你当前的代码,做这个调整:

 public void listf(String directoryName, ArrayList<File> files) { File directory = new File(directoryName); // get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList) { if (file.isFile()) { files.add(file); } else if (file.isDirectory()) { listf(file.getAbsolutePath(), files); } } } 

使用Apache公用程序中的FileUtils。

 listFiles public static Collection<File> listFiles(File directory, String[] extensions, boolean recursive) Finds files within a given directory (and optionally its subdirectories) which match an array of extensions. Parameters: directory - the directory to search in extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned. recursive - if true all subdirectories are searched as well Returns: an collection of java.io.File with the matching files 

你可以返回一个List而不是一个数组,事情变得更简单。

  public static List<File> listf(String directoryName) { File directory = new File(directoryName); List<File> resultList = new ArrayList<File>(); // get all the files from a directory File[] fList = directory.listFiles(); resultList.addAll(Arrays.asList(fList)); for (File file : fList) { if (file.isFile()) { System.out.println(file.getAbsolutePath()); } else if (file.isDirectory()) { resultList.addAll(listf(file.getAbsolutePath())); } } //System.out.println(fList); return resultList; }