Java Reference
In-Depth Information
public static long
getSize(File file) {
getSize
method
15
16
long
size =
0
;
// Store the total size of all files
17
18
if
( ) {
19
// All files and subdirectories
20
for
(
int
i =
0
; files !=
null
&& i < files.length; i++) {
21 size +=
file.isDirectory()
is directory?
all subitems
File[] files = file.listFiles();
getSize(files[i])
recursive call
;
// Recursive call
22 }
23 }
24
else
{
// Base case
25 size += file.length();
26 }
27
28
base case
return
size;
29 }
30 }
Enter a directory or a file:
48619631 bytes
c:\book
Enter a directory or a file:
172 bytes
c:\book\Welcome.java
c:\book\NonExistentFile
Enter a directory or a file:
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 (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 nonexis-
tent file.
testing all cases
20.16
What is the base case for the
getSize
method?
20.17
How does the program get all files and directories under a given directory?
20.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
The Towers of Hanoi problem is a classic problem that can be solved easily using
recursion, but it is difficult to solve otherwise.
Key
Point
The problem involves moving a specified number of disks of distinct sizes from one tower to
another while observing the following rules:
There are
n
disks labeled 1, 2, 3, . . . ,
n
and three towers labeled A, B, and C.
■
No disk can be on top of a smaller disk at any time.
■