Forums Register Login

Searching a given file name strating from a given root directory

+Pie Number of slices to send: Send
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:
+Pie Number of slices to send: Send
Check the methods of the File class in java.io
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
Can't .... do .... plaid .... So I did this tiny ad instead:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1001 times.
Similar Threads
I want to print on which level the file is present in given directory structure when using recursion
sendRedirect() to ROOT in tomcat
Reading a data file in an applet
Finding a file matching a pattern?
Diff betw canonical and absolute
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:24:04.