• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to search and return the existence of a file of a particular type on a path  RSS feed

 
sanat meher
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!