tags:

views:

367

answers:

4

Is there a way to search an entire computer for a String value representing a file name in Java? This would be without knowing the names of the drives on the computer.

+5  A: 

You can iterate through the file system by looking at file names, getting the contents if it's a directory, etc. recursively.

If the sticking point is how to get the drives on the computer, look at the File.listRoots() function to get a list of the drive letters.

ETA:

To be absolutely safe, you'll want to include some limits on recursive processing. It's possible to have loops in the file system with symbolic links and such (especially in LINUX/UNIX, but third party tools can enable this in Windows as well).

To make sure you don't get into a loop when dealing with symbolic links, use the File.getCanonicalPath methods to get the "real" path for the directory and keep track of all visited canonical paths. You could also use getCanonicalFile and keep track of all the files, but that's probably not needed unless you really want to avoid the occasional instance where you'll process the same file twice.

Eric Petroelje
I wonder if this would work in linux... since a drive is not a root but a folder in the root file system
Nuno Furtado
As the name indicates, the method will simply return that single root file system; it doesnt say anything about drives.
Michael Borgwardt
Watch out for links that could create an infinite recursion.@Nuno: Sure. A mounted drive will be returned when the directory containing its mount point is "listed".
erickson
@erickson : thx for the explanation. wondering if it is possible to detect that a file is just symbolic link
Nuno Furtado
@Nuno - updated my answer to clarify how to handle recursion because of symbolic links.
Eric Petroelje
+1  A: 

Also not forget exceptions in recursive processing. Some folders may not be accessible due to access right restrictions. Also, the Windows system folder "System Volume Information" cannot be entered in Windows Explorer, so I suppose it will throw an exception if you try to get inside programmaticaly.

User
A: 

You can use a recursive call through the entire file system: You can use the following methods of java.io.File:

  1. listRoots()): list the root files (In Windows it's the drives, on Mac OS X and linux it's '/').

  2. listFiles()): list the enclosing files of a directory

notnoop
+1  A: 

You can use the File object to determine whether you are looking at a file or a directory:

File file = new File("/"); //root

Then as you are recursing (or iterating depending on your preference) you have a simple check:

if(tempFile.isDirectory())
     //do recursive call on that directory
else
     //perform check on file name
amischiefr