程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java完成遞歸文件列表的辦法

java完成遞歸文件列表的辦法

編輯:關於JAVA

java完成遞歸文件列表的辦法。本站提示廣大學習愛好者:(java完成遞歸文件列表的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成遞歸文件列表的辦法正文


本文實例講述了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法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved