wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Searching a given file name strating from a given root directory Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Searching a given file name strating from a given root directory" Watch "Searching a given file name strating from a given root directory" New topic
Author

Searching a given file name strating from a given root directory

Ant Swa
Greenhorn

Joined: May 28, 2002
Posts: 13
Hi All,
I would like get some hint on above. Say, I want to search for a file "test.exe". I want to write a method that returns the exact path of the file if the given file name exist. I can pass the file name and the root directory as the parameters to this method.
May be this is a silly question and there is already a class for that and it is one line of coding.
:roll:


Anton
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
Check the methods of the File class in java.io


Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
timothy zimmerman
Ranch Hand

Joined: Jun 26, 2001
Posts: 149
Basically you could take the String representing your root directory. Use that to create a java.io.File.
Using the listFiles method of that File, create an array of Files in that directory.
(This array will contain both files and directories represented by java.io.File objects so you may want to create another method to actually get only files or only the directories)
You can then iterate through this array, using isFile you can determine if the indexed File is indeed a file and if the name equals the name of the file you are looking for. If you find it you are all set.
If you do not find it iterate through the array and recursively send each directory back to this method.
Sorry I did not include code. I thought I had something to recursively list files/directories but could not ifnd it.
If you still have questions I can try again to find it.
Ant Swa
Greenhorn

Joined: May 28, 2002
Posts: 13
Thanks Timothy,
I have used a similar approach. I wanted to know whether there is a short cut way of doing this.
I am from C++ background and I found that Java has lot of short cut ways of doing that kind of stuff compared to C. For example, take StringTokeniser class. I would write my own method to do some string manipulaions if I did not know about StringTokeniser which solves the problem within few lines of code.
 
jQuery in Action, 2nd edition
 
subject: Searching a given file name strating from a given root directory
 
Similar Threads
Reading a data file in an applet
sendRedirect() to ROOT in tomcat
I want to print on which level the file is present in given directory structure when using recursion
Diff betw canonical and absolute
Finding a file matching a pattern?