Java Reference
In-Depth Information
try
(
OutputStream
out
=
new
FileOutputStream
(
"/tmp/data.txt"
))
{
// work with the output stream...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
.
getMessage
());
}
The
finally
clause is no longer needed. Java automatically invokes
close()
on any
AutoCloseable
objects declared inside the argument list of the
try
block.
try with resources
can be used with any object that implements the
Closeable
interface, which includes almost every object you need to
dispose. So far, JavaMail
Transport
objects are only exceptions I've
encountered. Those still need to be disposed of explicitly.
Input Streams
Java's basic input class is
java.io.InputStream
:
public
abstract
class
InputStream
This class provides the fundamental methods needed to read data as raw bytes. These
are:
public
abstract
int
read
()
throws
IOException
public
int
read
(
byte
[]
input
)
throws
IOException
public
int
read
(
byte
[]
input
,
int
offset
,
int
length
)
throws
IOException
public
long
skip
(
long
n
)
throws
IOException
public
int
available
()
throws
IOException
public
void
close
()
throws
IOException
Concrete subclasses of
InputStream
use these methods to read data from particular
media. For instance, a
FileInputStream
reads data from a file. A
TelnetInputStream
reads data from a network connection. A
ByteArrayInputStream
reads data from an
array of bytes. But whichever source you're reading, you mostly use only these same six
methods. Sometimes you don't know exactly what kind of stream you're reading from.
For instance,
TelnetInputStream
is an undocumented class hidden inside the
sun.net
package. Instances of it are returned by various methods in the
java.net
package (e.g.,
the
openStream()
method of
java.net.URL
). However, these methods are declared to
return only
InputStream
, not the more specific subclass
TelnetInputStream
. That's
polymorphism at work once again. The instance of the subclass can be used transpar‐
ently as an instance of its superclass. No specific knowledge of the subclass is required.
The basic method of
InputStream
is the noargs
read()
method. This method reads a
single byte of data from the input stream's source and returns it as an
int
from 0 to 255.
End of stream is signified by returning -1. The
read()
method waits and blocks exe‐
cution of any code that follows it until a byte of data is available and ready to be read.