Java Reference
In-Depth Information
We would like to find the location of a file given its name. For example, given
TermPaper.odt
, we would like to know that it is located in
C:\Papers
. Given
FindFile.java
, we would like to know that it is located in
C:\JavaPrograms\
Recursion
. The general solution is to start at some root directory, such as
C:\
, and
to go through all the items in that directory. If an item is a file, check if it matches the
target. If an item is a directory, then make a recursive call to restart the search using
that directory as the new root directory.
Pseudocode of our recursive solution follows:
searchForFile(currentPath, targetFile)
if currentPath is not a directory
return error
for every item i in currentPath
if i is a directory
r = searchForFile(i, targetFile)
if r is a successful match
return r
if i is a file
if i matches targetFile
return path to file i
return target not found
To implement our algorithm, we need a way to determine if a path is a directory or
a file, and we need to find a way to get all of the items within a directory. Java's
File
object will do all of this for us. To use it, we must import
java.io.File
. Here is the
relevant constructor and methods:
CONSTRUCTORS AND METHODS
DESCRIPTION
File(String pathname)
The constructor takes a pathname and creates a
File
object corresponding to the file or directory
with that pathname.
String getAbsolutePath()
Returns the pathname of the
File
object, e.g.,
C:\Papers\TermPaper.odt.
String getName()
Returns the name of the
File
object, e.g.,
TermPaper.odt.
boolean isDirectory()
Returns
true
if the
File
object is a directory.
File[] listFiles()
If the
File
object is a directory then this returns
an array of
File
objects corresponding to all the
items within the directory.
Using the
File
object, we can implement the recursive algorithm to find a file. The
implementation in Display 11.11 returns an empty string if the target file is not found. If
the initial root folder supplied is not a directory, then an error message is returned. The
sample results assume the program runs using the directory structure given in Display 11.10.