Java Reference
In-Depth Information
continued
Very astute readers will note that the short primitive data type would also be fine
to represent a byte, as it ranges from -32,768 to 32,767 and thus has plenty of space
to represent both -1 and 0 to 255. The reason for this is simply because working
with
int
is is faster than shorts in the JVM (as this 32-bit type maps more closely
to underlying modern hardware), and that
int
has become sort of a standard
means to hold a byte of data. Secondly, you might also wonder why
read
returns
-1 instead of throwing an exception when the end of a stream is reached. Again a
good point, and this is due to historic reasons and standardized practices (coming
mainly from the world of the C programming language).
For
OutputStream
, we get:
➤
void write(int b)
: Writes the specified byte (represented using an
int
variable) to this
output stream.
➤
void write(byte[] b)
: Writes the specified byte array
b
to this output stream.
➤
void write(byte[] b, int off, int len)
: Writes
len
bytes from the
b
starting at offset
off
to this output stream.
➤
void close()
: Closes this output stream and releases any system resources associated with
this stream.
➤
void flush()
: “Flushes” this output stream, i.e. forces any buffered output bytes to be writ-
ten out.
It's worth underlining the fact that the
close
method appears in both the
InputStream
and
OutputStream
classes. It is extremely important to always close streams when you no longer need
them. In fact, this is so important that, even when an error occurs, you should still attempt to close
streams. Keeping streams open can lead to resource leaks, i.e. files remain opened by the JVM and
take up memory in your program. When the data source or destination is something other than a
file, the
close
method of the byte stream class might also be responsible for ensuring that every-
thing is tidied up correcly.
To get you started with byte streams, the following Try It Out shows you how to copy a file using
FileInputStream
and
FileOutputStream
, two basic byte stream classes aimed at working with files.
Copying Files with Byte Streams
try it out
In this Try It Out, you will copy a grocery list using byte streams.
1.
Create a new project in Eclipse if you haven't done so already.
2.
In the Eclipse Package Explorer, create a new file called
groceries.txt
within the project root
(not in the
src
folder). See Figure 8-3.
3.
Enter a grocery list in this TXT file and save it (one item per line). This example uses the following
shopping list:
Search WWH ::
Custom Search