Re: How to check if a directory exists? folder.exists() does not
work!
Ulf Meinhardt wrote:
I would like to check in a Java program if a certain directory exists.
The following does NOT work:
String fn = new String("C:\foobarnotexisting");
Others have pointed out some problems with this line. I'll just
add that `new String(existingString)' is almost always silly.
File root = new File(fn);
System.out.println("res=" + root.exists());
if (!root.exists()) {
System.out.println("not existing"); }
After compiling there is NO output.
Why?
Because the code you showed won't compile, hence it won't run
and produce output.
Oh, yes, we can all make the "obvious" completions and fill in
all the "obvious" bits you've omitted -- but when I do, I get output.
That means the bits and pieces I added are not the same as the bits
and pieces you subtracted, and that the problem probably lies in
those differing bits and pieces. Since I can't see what you didn't
show, I can't tell you what's wrong with it.
Next time you need help with a piece of code, please read
<http://sscce.org/>
before posting; it will make your message more meaningful and
reduce the time to solution.
How else can I check the existence?
The exists() method is the "right" way, although there are other
and more convoluted indirect means. You might, for example, just
sort of assume the file exists and start doing things with it, and
if you get a FileNotFoundException you'll know the assumption was
wrong. But that's silly; use exists().
Note that there is *no* way to be sure what the situation is if
exists() returns false. The file might actually exist, but reside
in a part of the file system you do not have permission to search,
or the file might exist on a CD that has been ejected, or something
of that kind. Roughly speaking, if exists() returns true you can be
confident that the file exists (or exist*ed* at the moment of inquiry),
but if it returns false all you can conclude is that the file is not
accessible to you -- it might exist, it might not, but you can't
really be sure.
--
Eric.Sosman@sun.com