Java's file-manipulation methods often indicate failure with a return value instead of throwing an exception. The Java Tutorials for Java 7 note:
Prior to the Java SE 7 release, the
java.io.File
class was the mechanism used for file I/O, but it had several drawbacks.
One of these drawbacks is that:
Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
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 . 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 Java Platform, Standard Edition 6 API Specification [API 2006] 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.
Code Block | ||
---|---|---|
| ||
File file = new File(args[0]);
file.delete();
|
...
This compliant solution checks the return value of delete()
.
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
Path file = new File(args[0]).toPath();
try {
Files.delete(file);
} catch (IOException x) {
System.out.println("Deletion failed");
// handle error
}
|
...
[API 2006] |
|
| |
Chapter 7, File I/O |