| Author |
how to search and return the existence of a file of a particular type on a path
|
sanat meher
Greenhorn
Joined: Nov 06, 2008
Posts: 18
|
|
Hi everyone,
Could anyone help me on the below problem..
I want to search a file with a particular extension(say .txt) on a particular location i.e inside a folder(C:\xyz\abc).
Here i want to search and return wheather any .txt file exists iniside the folder abc.
I tried the following code,but its not working because i have not specified any file name.(I have supplied only extension here)
File f1 = new File("C:\\WINDOWS\\*.txt");
System.out.println(f1.exists() ? "exists" : "does not exist");
I want a boolean value about wheather any .txt file exists or not in that folder.
Please guide me how to find that type of file in that location.
Thanks and regards,
Sanat
|
 |
Maneesh Godbole
Saloon Keeper
Joined: Jul 26, 2007
Posts: 8433
|
|
In pseudo code:
1) Create a file object from the required folder URL
2) Obtain an array of all the files in that folder
3) Iterate through the array. Check for extensions. If it is of the type you want, process it, else skip it.
When you iterate through the existing files, you need to remember that the current files can be a folder. In such scenarios recursion suggests itself.
|
[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Maneesh Godbole wrote:In pseudo code:
1) Create a file object from the required folder URL
2) Obtain an array of all the files in that folder
3) Iterate through the array. Check for extensions. If it is of the type you want, process it, else skip it.
Or in actual code, use File.listFiles in combination with a FileFilter or FilenameFilter. FileFilter would be better since it allows you to check for files only as well, filtering out directories at the same time.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Maneesh Godbole
Saloon Keeper
Joined: Jul 26, 2007
Posts: 8433
|
|
True,
But then I don't think it would work with files inside directories as well.
Maybe I misunderstood the OPs requirement, if the nested files should be returned or not.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
I understood not - it's like the command line's wildcards (*.txt). Those do not work with sub directories. And if it is needed, then all you need to do in the filter is allow both directories and files that end with .txt
|
 |
 |
|
|
subject: how to search and return the existence of a file of a particular type on a path
|
|
|