Java Reference
In-Depth Information
Display 11.11
Program to Recursively Find a File
1
import
java.io.File;
2
public class
FindFile
3 {
4
public static
String searchForFile(File dir, String target)
5 {
6 String result = "";
7
// If dir is not a directory, return
8
if
(!dir.isDirectory())
9
return
"Path is not a directory.";
10
11
// Check each item in the directory
12
for
(File folderItem : dir.listFiles())
13 {
14
// Recurse if it
'
s a directory
15
if
(folderItem.isDirectory())
16 {
17 result = searchForFile(folderItem,target);
18
// Return the result if it is not empty
19
if
(!result.equals(""))
20
return
result;
21 }
22
// If it
'
s a file, check for a match
23
else
24 {
25
if
(folderItem.getName().equals(target))
26
return
folderItem.getAbsolutePath();
27 }
28 }
29
// If we got here, nothing was found
30
return
"";
31 }
32
33
public static void
main(String[] args)
34 {
35
// The root folder to search
36 File rootFolder =
new
File("C:\\");
37 String result = searchForFile(rootFolder, "FindFile.java");
38
if
(!result.equals(""))
39 System.out.println(result);
40
else
41 System.out.println("File not found.");
42 }
43 }
Sample Dialogue Using Directory Structure of Display 11.10
C:\JavaPrograms\Recursion\FindFile.java