Link to home
Start Free TrialLog in
Avatar of ryno71
ryno71

asked on

Best Way using Java to see if a file/file type exists in a directory (platform independant ie not using unix find command)

Hi

What would be the best way using Java to see if a file/file type exists in a directory (platform independant ie not using unix find command)

thanks
ryno71
Avatar of sciuriware
sciuriware

String filename;

if(new File(filename).exists)
{
........................
}

;JOOP!
The 'filename' can be a full pathname (e.g. "/usr/lib/ghr/xyz.c") or a relative path (e.g. "../there/pqr.c"),
but in the latter case, you must know what your current directory is ( System.getProperty("user.dir");  ).
;JOOP!
Avatar of CEHJ
Equivalent to Unix find would normally involve recursion. This is how to do it platform-independently in pure Java.


http://javaalmanac.com/egs/java.io/TraverseTree.html

NB. method process(File) needs to be supplied by you
The questioner did not ask for a "deeper" search!

;JOOP!
SOLUTION
Avatar of hoomanv
hoomanv
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ryno71

ASKER

So I would have to create a filter for each of the files types I was looking for then.  Say I was looking for ryno.data, app71.txt, and day.obj... but they are all in the same directory as I placed them there.

Sorry, just mentioned find (unix) as I figured someone would say use that... but I want a java way. :)
All the files I would look for would be in one directory where I placed them...  but other have access to the directory which is why I need something that checks for the different type if they are there or not.

Thanks
ryno71
Using a filter is actually not efficient. You can just use File.exists for each case you have
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ryno71, why can't you just use my simple code 3 times, as you are looking for 3 files.
;JOOP!
Avatar of ryno71

ASKER

Actually Sciuriware, I could be looking for 3 to 38 files depending...

If it was just 3 files you are right using file.exists would be the easiest...

thanks for the help guys!
ryno71