Java实现列出目录下所有文件和文件夹

 1 package com.filetest;

 2 

 3 import java.io.File;

 4 import java.util.Scanner;

 5 

 6 public class fileview {

 7 

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

 9         

10         view();  //调用查看文件列表函数

11         

12     }

13 

14     private static void view() {

15         

16         Scanner scanner=new Scanner(System.in);

17         System.out.println("请输入一个目录:");

18         

19         String path=scanner.next();        //输入路径

20         

21         File file=new File(path);

22         

23         if(!file.exists()||!file.isDirectory()){    //判断路径是否存在

24             

25             if(path.equals("end"))                    //路径不存在则进入判断内,如果输入的不是end则递归调用重新输入

26             {

27                 System.out.println("程序结束,感谢使用!");

28                 System.exit(-1);

29             }

30             else

31             {

32                 System.out.println("输入的路径不存在,请重新输入!(输入end退出程序)");

33                 view();

34             }

35                         

36         }

37         

38         String[] names=file.list();    //将路径下的文件和目录存入字符串数组中

39         

40         int i=0;

41         int t=0;

42         String[] filename=new String[100];        //存放文件名字

43         String[] Directory=new String[100];        //存放目录名字

44         

45         for(String name:names){

46             

47             File files=new File(path+"\\"+name);

48             

49             if(files.isFile())        //判断是文件则存入文件字符串数组中

50             {                

51                 filename[i]=files.getName();

52                 i++;

53             }

54             else                    //判断是目录则存入目录字符串数组中

55             {

56                  Directory[t]=files.getName();

57                  t++;

58             }

59             

60         }

61         

62         System.out.println("该目录下一共有"+(i)+"个文件,它们的列表如下:");    //输出文件名

63         for(int x=0; x<i;x++){

64             System.out.println(filename[x]);

65             System.out.println();

66             

67         }

68         

69         System.out.println();

70         

71         System.out.println("该目录下一共有"+(t)+"个文件夹,它们的列表如下:");//输出目录名

72         for(int x=0; x<t;x++){

73             System.out.println(Directory[x]);

74             System.out.println();            

75         }

76         

77     }

78     

79 }

你可能感兴趣的:(java实现)