Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching a given file name strating from a given root directory

 
Ant Swa
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the methods of the File class in java.io
 
timothy zimmerman
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic