Java Reference
In-Depth Information
String
line
;
g
d
O
e
READ:
while
((
line
=
console
.
readLine
())
!=
null
)
{
// Check for special commands ("metas")
Matcher
m
=
SHELL_META_START
.
matcher
(
line
);
if
(
m
.
find
())
{
String
metaName
=
m
.
group
(
1
);
String
arg
=
m
.
group
(
2
);
doMeta
(
metaName
,
arg
);
continue
READ
;
}
System
.
out
.
println
(
line
);
}
}
catch
(
IOException
e
)
{
// Handle FileNotFoundException, etc. here
}
To output text to a file, we can use code like this:
File
f
=
new
File
(
System
.
getProperty
(
"user.home"
)
+
File
.
separator
+
".bashrc"
);
try
(
PrintWriter
out
=
new
PrintWriter
(
new
BufferedWriter
(
new
FileWriter
(
f
))))
{
out
.
println
(
"## Automatically generated config file. DO NOT EDIT"
);
}
catch
(
IOException
iox
)
{
// Handle exceptions
}
This older style of Java I/O has a lot of other functionality that is occasionally useful.
For example, to deal with text files, the
FilterInputStream
class is quite often use‐
ful. Or for threads that want to communicate in a way similar to the classic “piped”
I/O approach,
PipedInputStream
,
PipedReader
, and their write counterparts are
provided.
Throughout this chapter so far, we have used the language feature known as "
try
-
with-resources” (TWR). This syntax was briefly introduced in
“The try-with-
resources Statement” on page 63
, but it is in conjunction with operations like I/O
that it comes into its fullest potential, and it has granted a new lease on life to the
older I/O style.
try-with-resources Revisited
To make the most of Java's I/O capabilities, it is important to understand how and
when to use TWR. It is very easy to understand when code should use TWR—
whenever it is possible to do so.
Before TWR, resources had to be closed manually, and complex interactions
between resources that could fail to close led to buggy code that could leak
resources.