Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. package exercise2;
  2.  
  3. import java.io.File;
  4.  
  5. public class PrintJavaMain {
  6.     public static int depth = 0;
  7.  
  8.     // Recursive until all files below the original directory has been printed
  9.     public static void printAllJavaFiles(File file, int count) {
  10.             File[] subs = file.listFiles();
  11.             for (File f : subs) {
  12.                 if (f.isDirectory()) {
  13.                     printFile(f, 1);
  14.                     depth++;
  15.                     printAllJavaFiles(f, count);
  16.                     depth--;
  17.                 } else {
  18.                     printFile(f, 0);
  19.                 }
  20.  
  21.             }
  22.     }
  23.  
  24.     // Returns the extension name of the file "." included, example ".java"
  25.     public static String getFileExtension(File file) {
  26.         String name = file.getName();
  27.         int lastIndexOf = name.lastIndexOf(".");
  28.         if (lastIndexOf == -1) {
  29.             return "";
  30.         } else {
  31.             return name.substring(lastIndexOf);
  32.         }
  33.     }
  34.  
  35.     // Prints the directory and java files in the directory
  36.     public static void printFile ( File file, int type) {
  37.             String indentation = "";
  38.             // Indents the string
  39.             for (int i = 0; i < depth; i++) {
  40.                 indentation += "\t";
  41.             }
  42.             if (type == 1) {
  43.                 System.out.println(indentation + "Dir: "  + file.getName() + " " + (file.length() / 1024) + "KB");
  44.             } else {
  45.                 if(getFileExtension(file).equals(".java")) {
  46.                     System.out.println(indentation + "File: "  + file.getName() + " " + file.length() + " bytes");
  47.                 }
  48.             }
  49.     }
  50.  
  51.     public static void main(String[] args) {
  52.         File file = new File("C:\\Users\\lucas\\uni\\1dv600\\assignment_3\\directory");
  53.         printAllJavaFiles(file, 0);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement