Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated API 06 to API 14 citations, but this rule needs to be updated.

Java's file-manipulation methods often indicate failure with a return value instead of throwing an exception. Consequently, programs that ignore the return values from file operations often fail to detect that those operations have failed. Java programs must check the return values of methods that perform file I/O. This is a specific instance of rule EXP00-J. Do not ignore values returned by methods.

...

This noncompliant code example attempts to delete a specified file but gives no indication of its success. The Java Platform, Standard Edition 6, API Specification Specification [API 20062014] requires File.delete() to throw a SecurityException only when the program lacks authorization to delete the file. No other exceptions are thrown, so the deletion can silently fail.

...

This compliant solution checks the return value of delete().:

Code Block
bgColor#ccccFF
File file = new File("file");
if (!file.delete()) {
  System.out.println("Deletion failed");
}

...

This compliant solution uses the java.nio.file.Files.delete() method from Java SE 7 to delete the file.:

Code Block
bgColor#ccccFF
Path file = new File(args[0]).toPath();
try {
  Files.delete(file);
} catch (IOException x) {
  System.out.println("Deletion failed");
  // handleHandle error
}

The Java SE 7 Documentation [J2SE 2011] defines Files.delete() to throw the following exceptions:

Exception

Reason

NoSuchFileException

File does not exist

DirectoryNotEmptyException

File is a directory and could not otherwise be deleted because the directory is not empty

IOException

An I/O error occurs

SecurityException

In the case of the default provider and a security manager is installed, the SecurityManager.checkDelete(String) method is invoked to check delete access to the file

Since Because SecurityException is a runtime exception, it need not be declared. And Because NoSuchFileException and DirectoryNotExmptyException both inherit from IOException, they will be caught by the compliant solution's catch clause.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO02-J

Medium

Probable

Medium

P8

L2

Related Guidelines

Bibliography

[API 20062014]

File.delete()

[J2SE 2011]

Files.delete()

[Seacord 20052013]

Chapter 78, "File I/O"

 

...