fork download
  1. /*
  2. DirWriterに探索までさせているのは
  3. DirWriterにファイルへの出力だけを任せるのなら
  4. 別に新たなクラスを作ることなくたとえばFileWriter等に任せれば事足りるから
  5. DirListが窓口でDirWriterが実際の仕事というように分けてみた
  6. */
  7.  
  8. import java.io.*;
  9. import java.util.*;
  10.  
  11. public class DirList {
  12. public static void main(String[] args) throws FileNotFoundException {
  13. Scanner sc = new Scanner(System.in);
  14. System.out.print("一覧を生成するディレクトリ名: ");
  15. String dir = sc.nextLine();
  16. System.out.print("出力ファイル名: ");
  17. String out = sc.nextLine();
  18. try (DirWriter dw = new DirWriter(out)) {
  19. dw.list(dir);
  20. }
  21. sc.close();
  22. }
  23. }
  24.  
  25. class DirWriter implements AutoCloseable {
  26. private PrintWriter writer;
  27.  
  28. public DirWriter(String fileName) throws FileNotFoundException {
  29. writer = new PrintWriter(fileName);
  30. }
  31.  
  32. public void close() {
  33. writer.close();
  34. }
  35.  
  36. public void list(String fileName) throws FileNotFoundException {
  37. File f = new File(fileName);
  38. if (f.isDirectory()) {
  39. list(f);
  40. } else if (f.exists()) {
  41. writer.println(fileName);
  42. } else {
  43. throw new FileNotFoundException(fileName);
  44. }
  45. }
  46.  
  47. private void list(File dir) {
  48. Queue<File> que = new LinkedList<>();
  49. que.add(dir);
  50. while (! que.isEmpty()) {
  51. dir = que.remove();
  52. writer.println("Directory: " + dir.getName());
  53. File[] dirlist = dir.listFiles();
  54. Arrays.sort(dirlist, new Comparator<File>() {
  55. public int compare(File o1, File o2) {
  56. return o1.getName().compareToIgnoreCase(o2.getName());
  57. }
  58. });
  59. for (File f : dirlist) {
  60. writer.print(f.getName());
  61. if (f.isDirectory()) {
  62. writer.print(" はディレクトリです。");
  63. que.add(f);
  64. }
  65. writer.println();
  66. }
  67. }
  68. }
  69. }
  70.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty