dev@glassfish.java.net

Re: FindBugs errors - ignoring return value from filesystem operations

From: Byron Nevins <byron.nevins_at_oracle.com>
Date: Wed, 20 Apr 2011 00:33:20 -0700

FileUtils.mkdirsMaybe(File f)

returns true if the dir exists, false if it doesn't exist. It will try
to create it if necessary.


On 4/20/2011 12:03 AM, Bill Shannon wrote:
> 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.
>

-- 
Oracle <http://www.oracle.com>
Byron Nevins | Principal MTS
Phone: +1 6503958992 <tel:+1%206503958992>
Green Oracle <http://www.oracle.com/commitment> Oracle is committed to 
developing practices and products that help protect the environment