Java Reference
In-Depth Information
In fact, Oracle's engineers estimate that 60% of the resource handling code in the
initial JDK 6 release was incorrect. So, if even the platform authors can't reliably get
manual resource handling right, then all new code should definitely be using TWR.
The key to TWR is a new interface—
AutoCloseable
. This is a new interface
(appears in Java 7) that is a direct superinterface of
Closeable
. It marks a resource
that must be automatically closed, and for which the compiler will insert special
exception-handling code.
Inside a TWR resource clause, only declarations of objects that implement
Auto
Closeable
objects may appear—but the developer may declare as many as required:
try
(
BufferedReader
in
=
new
BufferedReader
(
new
FileReader
(
"profile"
));
PrintWriter
out
=
new
PrintWriter
(
new
BufferedWriter
(
new
FileWriter
(
"profile.bak"
))))
{
String
line
;
while
((
line
=
in
.
readLine
())
!=
null
)
{
out
.
println
(
line
);
}
}
catch
(
IOException
e
)
{
// Handle FileNotFoundException, etc. here
}
The consequences of this are that resources are automatically scoped to the
try
block. The resources (whether readable or writable) are automatically closed in the
correct order, and the compiler inserts exception handling that takes dependencies
between resources into account.
The overall effect of TWR is similar to C#'s
using
keyword, and the developer may
regard it as “finalization done right.” As noted in
“Finalization” on page 206
, new
code should never directly use the finalization mechanism, and should always use
TWR instead. Older code should be refactored to use TWR as soon as is practicable.
Problems with Classic I/O
Even with the welcome addition of
try
-with-resources, the
File
class and friends
have a number of problems that make them less than ideal for extensive use when
performing even standard I/O operations. For instance:
• “Missing methods” for common operations
• Does not deal with filenames consistently across platforms
• Fails to have a unified model for file attributes (e.g., modeling read/write
access)
• Difficult to traverse unknown directory structures
• No platform or OS-specific features