Documentation

The Java™ Tutorials
Hide TOC
Buffered Streams缓冲流
Trail: Essential Java Classes
Lesson: Basic I/O
Section: I/O Streams

Buffered Streams缓冲流

Most of the examples we've seen so far use unbuffered I/O.到目前为止,我们看到的大多数示例都使用无缓冲I/O。This means each read or write request is handled directly by the underlying OS.这意味着每个读或写请求都由底层操作系统直接处理。This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.这会降低程序的效率,因为每个这样的请求通常会触发磁盘访问、网络活动或其他相对昂贵的操作。

To reduce this kind of overhead, the Java platform implements buffered I/O streams.为了减少这种开销,Java平台实现了缓冲I/O流。Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty.缓冲输入流从称为缓冲器的存储器区域读取数据;仅当缓冲区为空时才调用本机输入API。Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.类似地,缓冲输出流将数据写入缓冲区,并且仅当缓冲区已满时才调用本机输出API。

A program can convert an unbuffered stream into a buffered stream using the wrapping idiom we've used several times now, where the unbuffered stream object is passed to the constructor for a buffered stream class.程序可以使用我们现在多次使用的包装习惯用法将未缓冲流转换为缓冲流,其中未缓冲流对象被传递给缓冲流类的构造函数。Here's how you might modify the constructor invocations in the CopyCharacters example to use buffered I/O:下面是如何修改CopyCharacters示例中的构造函数调用以使用缓冲I/O:

inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));

There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.有四个缓冲流类用于包装非缓冲流:BufferedInputStreamBufferedOutputStream创建缓冲字节流,而BufferedReaderBufferedWriter创建缓冲字符流。

Flushing Buffered Streams刷新缓冲流

It often makes sense to write out a buffer at critical points, without waiting for it to fill.在关键点写入缓冲区通常是有意义的,而不必等待它被填满。This is known as flushing the buffer.这称为刷新缓冲区。

Some buffered output classes support autoflush, specified by an optional constructor argument.某些缓冲输出类支持由可选构造函数参数指定的自动刷新When autoflush is enabled, certain key events cause the buffer to be flushed.启用自动刷新时,某些键事件会导致刷新缓冲区。For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format.例如,自动刷新PrintWriter对象在每次调用printlnformat时刷新缓冲区。See Formatting for more on these methods.有关这些方法的详细信息,请参阅格式化

To flush a stream manually, invoke its flush method.要手动刷新流,请调用其flush方法。The flush method is valid on any output stream, but has no effect unless the stream is buffered.flush方法对任何输出流都有效,但除非对流进行缓冲,否则无效。


Previous page: Character Streams
Next page: Scanning and Formatting