...
Consequently, file operations can silently fail if the methods' return values are ignored. Java programs must check the return values of method that perform file I/O (this is a specific instance of rule EXP00-J. Do not ignore values returned by methods.)
Noncompliant Code Example (delete()
)
This noncompliant code example attempts to delete a specified file, but gives no indication of its success. The [API 2006] requires File.delete()
to only throw a SecurityException
if the program is not authorized to delete the file. No other exceptions are thrown; so the deletion can silently fail.
Code Block | ||
---|---|---|
| ||
File file = /* initialize */ file.delete(); |
Compliant Solution
This compliant solution checks the return value of delete()
.
Code Block | ||
---|---|---|
| ||
File file = new File(args[0]); if (!file.delete()) { System.out.println("Deletion failed"); } |
Compliant Solution (Java 1.7)
This compliant solution uses the Files.delete()
method from Java 1.7 to delete the file.
...
Exception | Reason |
---|---|
| File does not exist |
| File is a directory and could not otherwise be deleted because the directory is not empty |
| An I/O error occurs |
| In the case of the default provider, and a security manager is installed, the |
Risk Assessment
Failure to check the return values of methods that perform file I/O can result in unexpected behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO09-J | medium | probable | high | P4 | L3 |
Automated Detection
TODO
Related Guidelines
Bibliography
[API 2006] | | |||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f3e6df5b7940ca21-a27e5869-4af5475e-bb3c913f-51f9e3645a6f8534ca73f84a"><ac:plain-text-body><![CDATA[ | [[J2SE 2011 | AA. Bibliography#J2SE 11]] | | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b91246db46846024-6e36e394-46c94d24-ae8da6bf-4e1bb01d3924b956a06e4b68"><ac:plain-text-body><![CDATA[ | [[Seacord 2005a | AA. Bibliography#Seacord 05]] | Chapter 7, "File I/O" | ]]></ac:plain-text-body></ac:structured-macro> |
...