Java Reference
In-Depth Information
The
while
loop counts the total number of bytes in the file. At the end,
the results are printed. Here is the output of the program when used on
itself:
318 bytes
You might be tempted to set
total
using
available
, but it won't work
on many kinds of streams. The
available
method returns the number of
bytes that can be read
without blocking.
For a file, the number of bytes
available is usually its entire contents. If
System.in
is a stream associ-
ated with a keyboard, the answer can be as low as zero; when there is
no pending input, the next
read
will block.
20.2.2.
OutputStream
The abstract class
OutputStream
is analogous to
InputStream
; it provides
an abstraction for writing bytes to a destination. Its methods are:
public abstract void
write(int b)
throws IOException
Writes
b
as a byte. The byte is passed as an
int
because it is
often the result of an arithmetic operation on a byte. Expres-
sions involving bytes are type
int
, so making the parameter
an
int
means that the result can be passed without a cast to
byte
. Note, however, that only the lowest 8 bits of the integer
are written. This method blocks until the byte is written.
public void
write(byte[] buf, int offset, int count)
tHRows IOExcep-
tion
Writes part of an array of bytes, starting at
buf[offset]
and
writing
count
bytes. This method blocks until the bytes have
been written.