【IO面试题】文件操作,如何列出某个目录下的所有文件?如何列出某个目录下的所有子目录?写个简单的例子

 1 import java.io.File;
 2 
 3 /**
 4  * IO面试题
 5  * 文件操作,如何列出某个目录下的所有文件?如何列出某个目录下的所有子目录?写个简单的例子
 6  * @author Peter
 7  *
 8  */
 9 public class IOSolution {
10     public static void getAllFile(String path){
11         File file=new File(path);
12         if(file.exists()){
13             if(file.isFile()){
14                 System.out.println(file.getName());
15             }else{
16                 File[] files=file.listFiles();
17                 if(files!=null){
18                     for(File f:files){
19                         getAllFile(f.getPath());
20                     }
21                 }
22             }
23         }
24     }
25     
26     public static void getAllDirectory(String path){
27         File file=new File(path);
28         if(file.exists()){
29             if(file.isDirectory()){
30                 System.out.println(file.getName());
31                 File[] files=file.listFiles();
32                 if(files!=null){
33                     for(File f:files){
34                         getAllDirectory(f.getPath());
35                     }
36                 }
37             }
38         }
39     }
40     
41     public static void main(String[] args){
42         getAllDirectory("C:\\Windows\\System32");
43     }
44 }

 

posted @ 2016-08-17 10:24  鑫大王爷  阅读(1112)  评论(0编辑  收藏  举报