欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现递归文件列表的方法

程序员文章站 2024-03-05 19:37:13
本文实例讲述了java实现递归文件列表的方法。分享给大家供大家参考。具体如下: filelisting.java如下: import java.util.*;...

本文实例讲述了java实现递归文件列表的方法。分享给大家供大家参考。具体如下:

filelisting.java如下:

import java.util.*;
import java.io.*;
/**
* recursive file listing under a specified directory.
* 
* @author javapractices.com
* @author alex wong
* @author anonymous user
*/
public final class filelisting {
 /**
 * demonstrate use.
 * 
 * @param aargs - <tt>aargs[0]</tt> is the full name of an existing 
 * directory that can be read.
 */
 public static void main(string... aargs) throws filenotfoundexception {
  file startingdirectory= new file(aargs[0]);
  list<file> files = filelisting.getfilelisting(startingdirectory);
  //print out all file names, in the the order of file.compareto()
  for(file file : files ){
   system.out.println(file);
  }
 }
 /**
 * recursively walk a directory tree and return a list of all
 * files found; the list is sorted using file.compareto().
 *
 * @param astartingdir is a valid directory, which can be read.
 */
 static public list<file> getfilelisting(
  file astartingdir
 ) throws filenotfoundexception {
  validatedirectory(astartingdir);
  list<file> result = getfilelistingnosort(astartingdir);
  collections.sort(result);
  return result;
 }
 // private //
 static private list<file> getfilelistingnosort(
  file astartingdir
 ) throws filenotfoundexception {
  list<file> result = new arraylist<file>();
  file[] filesanddirs = astartingdir.listfiles();
  list<file> filesdirs = arrays.aslist(filesanddirs);
  for(file file : filesdirs) {
   result.add(file); //always add, even if directory
   if ( ! file.isfile() ) {
    //must be a directory
    //recursive call!
    list<file> deeperlist = getfilelistingnosort(file);
    result.addall(deeperlist);
   }
  }
  return result;
 }
 /**
 * directory is valid if it exists, does not represent a file, and can be read.
 */
 static private void validatedirectory (
  file adirectory
 ) throws filenotfoundexception {
  if (adirectory == null) {
   throw new illegalargumentexception("directory should not be null.");
  }
  if (!adirectory.exists()) {
   throw new filenotfoundexception("directory does not exist: " + adirectory);
  }
  if (!adirectory.isdirectory()) {
   throw new illegalargumentexception("is not a directory: " + adirectory);
  }
  if (!adirectory.canread()) {
   throw new illegalargumentexception("directory cannot be read: " + adirectory);
  }
 }
}

希望本文所述对大家的java程序设计有所帮助。