Skip to content

Instantly share code, notes, and snippets.

@bytecodeman bytecodeman/DirectoryInfoUtility.java Secret
Last active Nov 14, 2018

Embed
What would you like to do?
CSC-220 Recursive Directory Info Utility
/*
* Name: Prof. Antonio C. Silvestri
* Date: 11/9/2018
* Course Number: CSC-220
* Course Name: Data Structures and Algorithms
* Email: silvestristcc.edu
*
* Write a program that prompts the user to enter a directory and displays
* the number of the files and directories in the directory.
*/
import java.io.File;
import java.util.Scanner;
public class DirectoryInfoUtility {
private final static int FILECOUNT = 0;
private final static int DIRECTORYCOUNT = 1;
private final static int FILESIZE = 2;
private static long[] getDirectoryInfo(File file) {
long fileCount = 0;
long dirCount = 0;
long fileSize = 0;
if (file.exists())
if (file.isDirectory()) {
dirCount++;
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
long[] di = getDirectoryInfo(files[i]);
fileCount += di[FILECOUNT];
dirCount += di[DIRECTORYCOUNT];
fileSize += di[FILESIZE];
}
}
else {
fileCount++;
fileSize += file.length();
}
return new long[] { fileCount, dirCount, fileSize };
}
// Textbook Code
public static long getSize(File file) {
long size = 0; // Store the total size of all files
if (file.isDirectory()) {
File[] files = file.listFiles(); // All files and subdirectories
for (int i = 0; i < files.length; i++) {
size += getSize(files[i]); // Recursive call
}
} else { // Base case
size += file.length();
}
return size;
}
// **********************************************
private static void process(Scanner sc, String args[]) {
System.out.print("Enter a directory or a file: ");
String directory = sc.nextLine();
long[] dirInfo = getDirectoryInfo(new File(directory));
System.out.printf("%,d Files, %,d Folders, %,d Size\n", dirInfo[FILECOUNT], dirInfo[DIRECTORYCOUNT],
dirInfo[FILESIZE]);
long size = getSize(new File(directory));
System.out.println(size);
}
// **********************************************
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.equalsIgnoreCase("Y");
}
// **********************************************
public static void main(String args[]) {
final String TITLE = "Directory Info Utility V1.0";
final String CONTINUE_PROMPT = "Do this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.