Posted By

marczxc on 09/25/10


Tagged

directory scan


Versions (?)

Scan Directory


 / Published in: Java
 

  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class Directory {
  5.  
  6. private String name;
  7.  
  8. public Directory() {
  9. this(".");
  10. }
  11.  
  12. public Directory(String name) {
  13. this.name = name;
  14. }
  15.  
  16. public Vector<FileInfo> scanDir() throws IOException {
  17. return scanDir(new File("."));
  18. }
  19.  
  20. public Vector<FileInfo> scanDir(String name) throws IOException {
  21. return scanDir(new File(name));
  22. }
  23.  
  24. private Vector<FileInfo> scanDir(File dir) throws IOException {
  25. if(!dir.exists())
  26. throw new IOException("La cartella non esiste");
  27.  
  28. Vector<FileInfo> elenco = new Vector<FileInfo>();
  29. for (File file : dir.listFiles()) {
  30. if (file.isFile())
  31. elenco.addElement(new FileInfo(file.getName(), file.getParent(), file.length()));
  32. else if (file.isDirectory())
  33. elenco.addAll(scanDir(file));
  34. }
  35. return elenco;
  36. }
  37.  
  38. public static void main(String[] args) throws IOException {
  39. Scanner input = new Scanner(System.in);
  40.  
  41. System.out.println("Inserire il nome della directory da analizzare (premere BARRA SPAZIO se si vuole analizzare tutta la directory): ");
  42. String nameOfDir = input.nextLine();
  43. Directory a;
  44.  
  45. if(nameOfDir.equals(" ")) {
  46. a = new Directory();
  47. for(FileInfo info : a.scanDir()){
  48. System.out.println(info);
  49. System.out.println("");
  50. }
  51. } else {
  52. a = new Directory(nameOfDir);
  53. for(FileInfo info : a.scanDir(nameOfDir)){
  54. System.out.println(info);
  55. System.out.println("");
  56. }
  57. }
  58.  
  59.  
  60. }
  61. }
  62.  
  63. class FileInfo {
  64.  
  65. private String name;
  66. private String dir;
  67. private long dimensione;
  68.  
  69. public FileInfo(String name, String dir, long dim) {
  70. this.name = name;
  71. this.dir = dir;
  72. dimensione = dim;
  73. }
  74.  
  75. public String toString() {
  76. return "Nome: " + name + "\nPath: " + dir + "\nDimensione: " + dimensione + " byte";
  77. }
  78.  
  79. }

Report this snippet  

You need to login to post a comment.