Java遍历一个目录下的所有文件
 

Java工具中为我们提供了一个用于管理文件系统的类,这个类就是File类,File类与其他流类不同的是,流类关心的是文件的内容,而File类关心的是磁盘上文件的存储。

一,File类有多个构造器,常用的构造器有:

二,获得文件的权限属性:

1,表明文件是否可读,可写,可执行

2,设置文件的可读,可写,可执行

3,删除文件

4,判断文件是否存在

5,获得文件路径名

6,判断File为文件还是目录

7,获得File对象包含的文件名和目录名

File还有许多方法属性,跟多的可以查看API文档

现在,使用File类来遍历一个目录下的所有文件,我的程序过程为:

程序如下:

  1. import java.io.File;
  2. import java.io.IOException;
  3. public class DirErgodic {
  4. private static int depth=1;
  5. public static void find(String pathName,int depth) throws IOException{
  6. int filecount=0;
  7. //获取pathName的File对象
  8. File dirFile = new File(pathName);
  9. //判断该文件或目录是否存在,不存在时在控制台输出提醒
  10. if (!dirFile.exists()) {
  11. System.out.println("do not exit");
  12. return ;
  13. }
  14. //判断如果不是一个目录,就判断是不是一个文件,时文件则输出文件路径
  15. if (!dirFile.isDirectory()) {
  16. if (dirFile.isFile()) {
  17. System.out.println(dirFile.getCanonicalFile());
  18. }
  19. return ;
  20. }
  21. for (int j = 0; j < depth; j++) {
  22. System.out.print("  ");
  23. }
  24. System.out.print("|--");
  25. System.out.println(dirFile.getName());
  26. //获取此目录下的所有文件名与目录名
  27. String[] fileList = dirFile.list();
  28. int currentDepth=depth+1;
  29. for (int i = 0; i < fileList.length; i++) {
  30. //遍历文件目录
  31. String string = fileList[i];
  32. //File("documentName","fileName")是File的另一个构造器
  33. File file = new File(dirFile.getPath(),string);
  34. String name = file.getName();
  35. //如果是一个目录,搜索深度depth++,输出目录名后,进行递归
  36. if (file.isDirectory()) {
  37. //递归
  38. find(file.getCanonicalPath(),currentDepth);
  39. }else{
  40. //如果是文件,则直接输出文件名
  41. for (int j = 0; j < currentDepth; j++) {
  42. System.out.print("   ");
  43. }
  44. System.out.print("|--");
  45. System.out.println(name);
  46. }
  47. }
  48. }
  49. public static void main(String[] args) throws IOException{
  50. find("D:\\MongoDB", depth);
  51. }
  52. }

测试截图:

Java遍历一个目录下的所有文件-LMLPHP

04-18 19:56
查看更多