获取指定文件夹下的所有文件名

递归获取某目录下的所有文件名,路径。

 1 package test;

 2 

 3 import java.io.File;

 4 

 5 public class GetFileName{

 6 

 7     public static void main(String[] args) {

 8         // This is the path where the file's name you want to take.

 9         String path = "C:\\ProgramData";

10         getFile(path);

11     }

12 

13     private static void getFile(String path) {

14         // get file list where the path has

15         File file = new File(path);

16         // get the folder list

17         File[] array = file.listFiles();

18 

19         if (array != null)     //没权限访问,则会报错文件为null

20             for (int i = 0; i < array.length; i++) {

21                 if (array[i].isFile()) {    //可以这样判断 if (obj instanceof File) {  

22                     // only take file name

23                     System.out.println("^^^^^" + array[i].getName());

24                     // take file path and name

25                     System.out.println("#####" + array[i]);

26                     // take file path and name

27                     System.out.println("*****" + array[i].getPath());

28                 } else if (array[i] instanceof File) {

29                     getFile(array[i].getPath());

30                 }

31             }

32     }

33 }

若要返回这些东西,

则:

package test;



import java.io.File;



/*** 

 * 获取指定目录下的所有的文件(不包括文件夹),采用了递归 

 *  

 * @param obj 

 * @return 

 */  

public static ArrayList<File> getListFiles(Object obj) {  

    File directory = null;  

    if (obj instanceof File) {  

        directory = (File) obj;  

    } else {  

        directory = new File(obj.toString());  

    }  

    ArrayList<File> files = new ArrayList<File>();  

    if (directory.isFile()) {  

        files.add(directory);  

        return files;  

    } else if (directory.isDirectory()) {  

        File[] fileArr = directory.listFiles();  

        for (int i = 0; i < fileArr.length; i++) {  

            File fileOne = fileArr[i];  

            files.addAll(getListFiles(fileOne));  

        }  

    }  

    return files;  

}  

参考:  http://blog.csdn.net/tomorrowzm/article/details/3693653 

http://hw1287789687.iteye.com/blog/1946488 

你可能感兴趣的:(文件夹)