FILE建立指定后缀名的文件列表

短命女 2022-06-17 06:40 299阅读 0赞
  1. /*
  2. 将一个指定目录下的java文件的绝对路径存储到一个文本文件中
  3. 建立一个java文件列表文件
  4. 思路:
  5. 1:对指定的目录进行递归。
  6. 2:获取递归过程的java文件的路径
  7. 3:将这些路径存储到集合中
  8. 4:将集合中的数据写入到一个文件中
  9. */
  10. import java.io.*;
  11. import java.util.*;
  12. class JavaFileList
  13. {
  14. private static File fw;
  15. private static ArrayList<File> al;
  16. public static void main(String[] args)throws IOException
  17. {
  18. al = new ArrayList<File>(); //保存文件列表
  19. javaFileList(new File("e:\\code\\ABC"),al);
  20. writeToFile(al); //写到文件中
  21. }
  22. public static void javaFileList(File dir,List<File> list)
  23. {
  24. File[] files = dir.listFiles();
  25. for(File file:files)
  26. {
  27. if(file.isDirectory())
  28. {
  29. javaFileList(file,list);
  30. }
  31. else
  32. {
  33. if(file.getName().endsWith(".java"))
  34. al.add(file);
  35. }
  36. }
  37. }
  38. public static void writeToFile(List<File> list)throws IOException
  39. {
  40. BufferedWriter bw = null;
  41. try
  42. {
  43. fw = new File("javafilelist.txt");
  44. bw = new BufferedWriter(new FileWriter(fw));
  45. int line = 0;
  46. for(File file:list)
  47. {
  48. line++;
  49. String path = file.getAbsolutePath();
  50. bw.write((int)line+": ");
  51. bw.write(path);
  52. bw.newLine();
  53. bw.flush();
  54. }
  55. }
  56. catch (IOException e)
  57. {
  58. throw e;
  59. }
  60. finally
  61. {
  62. if(bw != null)
  63. {
  64. try
  65. {
  66. bw.close();
  67. }
  68. catch (IOException e)
  69. {
  70. throw e;
  71. }
  72. }
  73. }
  74. }
  75. }

发表评论

表情:
评论列表 (有 0 条评论,299人围观)

还没有评论,来说两句吧...

相关阅读