-
newbie needs help...
Hi everyone,
I'm a student currently studying IT and now started java. I have been thrown into the deep end and given some java questions to do over the easter period and seem to be struggling. At the moment there is nobody in university to speak to, so thought you guys would be the best solution and was told to use any resources available.
This is what my lecturer wrote word for word and I don't fully understand what it means? Any help would be greatly appreciated...
"Complete these classes to provide a command line application Diskusage which outputs to standard output a list of the contents (both files and directories) of a specified root directory and all its subdirectories. Each line of output should either the file size in bytes, or the total size of all files within the directory"
This is the first command 'FileUtilities' in the question:
/* add required import statements */
public class FileUtilities {
/* complete method declaration */ diskUsage( File f ) {
/* complete method */
}
/* Add further methods? */
}
This is the second 'DiskUsage' command:
public class DiskUsage {
public static void main( String[] args ) {
/* error checking? */
/* set type */ size = FileUtilities.diskUsage( args[0] );
System.out.println( "Total size of " + args[0]
+ " is " + size );
}
}
Thanks,
Vicky.
-
Code:
import java.io.File;
public class DiskUsage {
public static void main( String[] args ) {
//args = new String[]{ "." }; // current directory
if(args.length == 0) {
System.out.println("Usage: specify a path/folder_or_file");
System.exit(1);
}
File file = new File(args[0]);
if(!file.exists()) {
System.out.println("File for " + args[0] + " does not exist");
System.exit(1);
}
long size = FileUtilities.diskUsage( file );
System.out.println( "Total size of " + file.getPath() +
" is " + size );
}
}
class FileUtilities {
static long totalSize;
public static long diskUsage( File f ) {
if(!f.isDirectory()) {
return f.length();
} else {
totalSize = 0;
traverseFiles(f);
return totalSize;
}
}
private static void traverseFiles(File file) {
File[] files = file.listFiles();
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
System.out.println("---- folder " +
files[i].getName() +
" ----");
traverseFiles(files[i]);
} else {
totalSize += files[i].length();
System.out.println(files[i].getName() +
" " + files[i].length());
}
}
}
}
-
Thank-you very much for all your help.
Vicky