Working with Streams 使用流

Working with Streams


Along with File and RandomAccessFile, Java uses streams to perform I/O operations. A stream is an
ordered sequence of bytes of arbitrary length. Bytes flow over an output stream from an application
to a destination and flow over an input stream from a source to an application. Figure 11-2 illustrates
these flows.

application write  destination

                  * * *

         output stream

source  read  application          
             * * *
        input stream

Figure 11-2. Conceptualizing output and input streams as flows of bytes

Note Java’s use of the word stream is analogous to stream of water, stream of electrons, and so on.

注意 Java的单词stream 的使用类似于水流、电流等等。

Java recognizes various stream destinations, such as byte arrays, files, screens, sockets (network
endpoints), and thread pipes. Java also recognizes various stream sources. Examples include byte
arrays, files, keyboards, sockets, and thread pipes. (I will discuss sockets in Chapter 12.)


Stream Classes Overview

Stream Classes纵览


The java.io package provides several output stream and input stream classes that are descendants
of the abstract OutputStream and InputStream classes. Figure 11-3 reveals the hierarchy of output
stream classes.


Figure 11-3. All output stream classes except for PrintStream are denoted by their OutputStream suffixes
Figure 11-4 reveals the hierarchy of input stream classes.
Figure 11-4. Note that LineNumberInputStream and StringBufferInputStream are deprecated

LineNumberInputStream and StringBufferInputStream have been deprecated because they don’t
support different character encodings, a topic I discuss later in this chapter. LineNumberReader and
StringReader are their replacements. (I discuss readers later in this chapter.)


Note PrintStream is another class that should be deprecated because it doesn’t support different
character encodings; PrintWriter is its replacement. However, it’s doubtful that Oracle (and Google) will
deprecate this class because PrintStream is the type of the System class’s out and err class fields, and
too much legacy code depends upon this fact.

然而,不能肯定Oracle(或 Google)会弃用这个类,因为PrintStream是System类的out和err 类字段,并且太多遗产代码依赖这个事实。

Other Java packages provide additional output stream and input stream classes. For example,
java.util.zip provides four output stream classes that compress uncompressed data into various
formats and four matching input stream classes that uncompress compressed data from the same
formats:


 CheckedOutputStream
 CheckedInputStream
 DeflaterOutputStream
 GZIPOutputStream
 GZIPInputStream
 InflaterInputStream
 ZipOutputStream
 ZipInputStream


Also, the java.util.jar package provides a pair of stream classes for writing content to a JAR file
and for reading content from a JAR file:


 JarOutputStream
 JarInputStream


In the next several sections, I take you on a tour of most of java.io’s output stream and input stream
classes, beginning with OutputStream and InputStream.


OutputStream and InputStream


Java provides the OutputStream and InputStream classes for performing stream I/O. OutputStream is
the superclass of all output stream subclasses. Table 11-7 describes OutputStream’s methods.

Table 11-7. OutputStream Methods
Method Description
void close() Closes this output stream and releases any platform resources associated with the
stream. This method throws IOException when an I/O error occurs.


void flush() Flushes this output stream by writing any buffered output bytes to the destination.
If the intended destination of this output stream is an abstraction provided by the
underlying platform (for example, a file), flushing the stream only guarantees that
bytes previously written to the stream are passed to the underlying platform for
writing; it doesn’t guarantee that they’re actually written to a physical device such
as a disk drive. This method throws IOException when an I/O error occurs.


void write(byte[] b) Writes b.length bytes from byte array b to this output stream. In general, write(b)
behaves as if you specified write(b, 0, b.length). This method throws
NullPointerException when b is null and IOException when an I/O error occurs.
void write(byte[] b,int off, int len)
Writes len bytes from byte array b starting at offset off to this output stream.
This method throws NullPointerException when b is null; java.lang.
IndexOutOfBoundsException when off is negative, len is negative, or off + len is
greater than b.length; and IOException when an I/O error occurs.
void write(int b) Writes byte b to this output stream. Only the 8 low-order bits are written; the 24
high-order bits are ignored. This method throws IOException when an I/O error
occurs.


Note The close() method automatically flushes the output stream. If an application ends before close()
is called, the output stream is automatically closed and its data is flushed.


InputStream is the superclass of all input stream subclasses. Table 11-8 describes InputStream’s
methods.

Table 11-8. InputStream Methods
Method Description
int available() Returns an estimate of the number of bytes that can be read from this input stream
via the next read() method call (or skipped over via skip()) without blocking the
calling thread. This method throws IOException when an I/O error occurs.
It’s never correct to use this method’s return value to allocate a buffer for holding all
of the stream’s data because a subclass might not return the total size of the stream.
void close() Closes this input stream and releases any platform resources associated with the
stream. This method throws IOException when an I/O error occurs.
void mark(int
readlimit)
Marks the current position in this input stream. A subsequent call to reset()
repositions this stream to the last marked position so that subsequent read
operations re-read the same bytes. The readlimit argument tells this input stream
to allow that many bytes to be read before invalidating this mark (so that the stream
cannot be reset to the marked position).
boolean
markSupported()
Returns true when this input stream supports mark() and reset(); otherwise,
returns false.
int read() Reads and returns (as an int in the range 0 to 255) the next byte from this input
stream, or returns -1 when the end of the stream is reached. This method blocks until
input is available, the end of the stream is detected, or an exception is thrown.

It throws IOException when an I/O error occurs.

输入数据可用检测到流末尾或者抛出异常前,此方法一直阻塞


int read(byte[] b) Reads some number of bytes from this input stream and stores them in byte array b.
Returns the number of bytes actually read (which might be less than b’s length but is
never more than this length), or returns -1 when the end of the stream is reached (no
byte is available to read). This method blocks until input is available, the end of the
stream is detected, or an exception is thrown. It throws NullPointerException when
b is null and IOException when an I/O error occurs.


int read(byte[] b,int off, int len)
Reads no more than len bytes from this input stream and stores them in byte array
b, starting at the offset specified by off. Returns the number of bytes actually read
(which might be less than len but is never more than len), or returns -1 when the
end of the stream is reached (no byte is available to read). This method blocks until
input is available, the end of the stream is detected, or an exception is thrown. It
throws NullPointerException when b is null; IndexOutOfBoundsException when off
is negative, len is negative, or len is greater than b.length - off; and IOException
when an I/O error occurs.


void reset() Repositions this input stream to the position at the time mark() was last called. This
method throws IOException when this input stream has not been marked or the mark
has been invalidated.

long skip(long n) Skips over and discards n bytes of data from this input stream. This method might
skip over some smaller number of bytes (possibly zero), for example, when the end
of the file is reached before n bytes have been skipped. The actual number of bytes
skipped is returned. When n is negative, no bytes are skipped. This method throws
IOException when this input stream doesn’t support skipping or when some other

I/O error occurs.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值