java實現(xiàn)遞歸文件列表的方法
更新時間:2015年07月21日 17:06:26 作者:華宰
這篇文章主要介紹了java實現(xiàn)遞歸文件列表的方法,實例分析了java采用遞歸算法遍歷文件的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了java實現(xiàn)遞歸文件列表的方法。分享給大家供大家參考。具體如下:
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程序設計有所幫助。
相關文章
Java多線程之readwritelock讀寫分離的實現(xiàn)代碼
這篇文章主要介紹了Java多線程之readwritelock讀寫分離的相關內容,文中涉及具體實例代碼,具有一定參考價值,需要的朋友可以了解下。2017-10-10解決在Idea 2020.2下使用 Lombok的注解不生效的問題(插件安裝了,依賴也寫了,自動注解也設置了)
這篇文章主要介紹了在Idea 2020.2下使用 Lombok的注解不生效的問題(插件安裝了,依賴也寫了,自動注解也設置了),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08仿釘釘流程輕松實現(xiàn)JSON轉BPMN完整實現(xiàn)過程示例
這篇文章主要為大家介紹了仿釘釘流程輕松實現(xiàn)JSON轉BPMN完整實現(xiàn)過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08