java实现递归文件列表的方法
本文实例讲述了java实现递归文件列表的方法。分享给大家供大家参考。具体如下:
FileListing.java如下:
importjava.util.*; importjava.io.*; /** *Recursivefilelistingunderaspecifieddirectory. * *@authorjavapractices.com *@authorAlexWong *@authoranonymoususer */ publicfinalclassFileListing{ /** *Demonstrateuse. * *@paramaArgs-<tt>aArgs[0]</tt>isthefullnameofanexisting *directorythatcanberead. */ publicstaticvoidmain(String...aArgs)throwsFileNotFoundException{ FilestartingDirectory=newFile(aArgs[0]); List<File>files=FileListing.getFileListing(startingDirectory); //printoutallfilenames,inthetheorderofFile.compareTo() for(Filefile:files){ System.out.println(file); } } /** *RecursivelywalkadirectorytreeandreturnaListofall *Filesfound;theListissortedusingFile.compareTo(). * *@paramaStartingDirisavaliddirectory,whichcanberead. */ staticpublicList<File>getFileListing( FileaStartingDir )throwsFileNotFoundException{ validateDirectory(aStartingDir); List<File>result=getFileListingNoSort(aStartingDir); Collections.sort(result); returnresult; } //PRIVATE// staticprivateList<File>getFileListingNoSort( FileaStartingDir )throwsFileNotFoundException{ List<File>result=newArrayList<File>(); File[]filesAndDirs=aStartingDir.listFiles(); List<File>filesDirs=Arrays.asList(filesAndDirs); for(Filefile:filesDirs){ result.add(file);//alwaysadd,evenifdirectory if(!file.isFile()){ //mustbeadirectory //recursivecall! List<File>deeperList=getFileListingNoSort(file); result.addAll(deeperList); } } returnresult; } /** *Directoryisvalidifitexists,doesnotrepresentafile,andcanberead. */ staticprivatevoidvalidateDirectory( FileaDirectory )throwsFileNotFoundException{ if(aDirectory==null){ thrownewIllegalArgumentException("Directoryshouldnotbenull."); } if(!aDirectory.exists()){ thrownewFileNotFoundException("Directorydoesnotexist:"+aDirectory); } if(!aDirectory.isDirectory()){ thrownewIllegalArgumentException("Isnotadirectory:"+aDirectory); } if(!aDirectory.canRead()){ thrownewIllegalArgumentException("Directorycannotberead:"+aDirectory); } } }
希望本文所述对大家的java程序设计有所帮助。