Java Reference
In-Depth Information
14
15
public static long getSize(File file) {
getSize method
16
long size = 0 ; // Store the total size of all files
17
18 if (file.isDirectory()) {
19 File[] files = file.listFiles(); // All files and subdirectories
20 for ( int i = 0 ; files != null && i < files.length; i++) {
21 size += getSize(files[i]); // Recursive call
22 }
23 }
24 else { // Base case
25 size += file.length();
26 }
27
28
is directory?
all subitems
recursive call
base case
return size;
29 }
30 }
Enter a directory or a file: c:\book
48619631 bytes
Enter a directory or a file: c:\book\Welcome.java
172 bytes
Enter a directory or a file: c:\book\NonExistentFile
0 bytes
If the file object represents a directory (line 18), each subitem (file or subdirectory) in the
directory is recursively invoked to obtain its size (line 21). If the file object represents a file
(line 24), the file size is obtained and added to the total size (line 25).
What happens if an incorrect or a nonexistent directory is entered? The program will detect
that it is not a directory and invoke file.length() (line 25), which returns 0 . Thus, in this
case, the getSize method will return 0 .
Tip
To avoid mistakes, it is a good practice to test all cases. For example, you should test
the program for an input of file, an empty directory, a nonexistent directory, and a
nonexistent file.
testing all cases
18.16 What is the base case for the getSize method?
18.17 How does the program get all files and directories under a given directory?
18.18 How many times will the getSize method be invoked for a directory if the directory
has three subdirectories and each subdirectory has four files?
Check
Point
18.19
Will the program work if the directory is empty (i.e., it does not contain any files)?
18.20
Will the program work if line 20 is replaced by the following code?
for ( int i = 0 ; i < files.length; i++)
 
 
Search WWH ::




Custom Search