dev@glassfish.java.net

Re: FindBugs errors - ignoring return value from filesystem operations

From: Bill Shannon <bill.shannon_at_oracle.com>
Date: Wed, 20 Apr 2011 00:03:46 -0700

If you need it to be a directory, and it's actually a file,
f.exists() isn't telling you what you need to know.

f.isDirectory() is true if it exists *and* it's a directory.


Marina Vatkina wrote on 04/19/2011 03:55 PM:
> Bill,
>
> Would it be wrong to check if (!f.exists() && !f.mkdirs()) Or may be even if
> (!(f.exists() && f.isDirectory) || !f.mkdirs())?
>
> thanks,
> -marina
>
> Bill Shannon wrote:
>> FindBugs complains if you ignore the error return value from a filesystem
>> operation, e.g.,
>>
>> f.mkdirs();
>>
>> Be careful when fixing these errors. In many cases it's ok if the operation
>> fails, e.g., if the directory already exists. The fix for the above is NOT
>>
>> if (!f.mkdirs())
>> error(); // WRONG
>>
>> A better fix is
>>
>> if (!f.isDirectory() && !f.mkdirs())
>> error();
>>
>>
>>
>> Also, be careful with filesystem operations that might behave differently
>> on Windows. I recently got bit by some permission changing code. When I
>> fixed it to fail if the permissions weren't changed, it failed on Windows.
>> The permission changing method as currently implemented always fails on
>> Windows. Ouch. In this case I chose to always ignore the return value.