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

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

 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 

转载于:https://www.cnblogs.com/liu-qing/p/3930955.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值