【Java使用手册】-04 Buffered Streams
本文包括一部分内容:
- Oracle官网Java教程-Buffered Streams 和译文(译文属于个人理解);
part1. 教材及翻译
Buffered Streams
Most of the examples we've seen so far use unbuffered 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. 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. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
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:译:缓冲流
到目前为止,我们看到的大多数示例都是未缓冲 I/O。这意味着每个读或写请求都由底层操作系统直接处理。这会让一个程序更低效,因为每一个这样的请求常常会触发硬盘访问,网络活动,或其他一些相对昂贵的操作。
为了减少这种开销,Java 平台实现了缓冲的 I/O 流。被缓冲的输入流从一个叫做缓冲区的内存区域读取数据,只有当缓冲区是空的时候才调用本机的输入API。类似地,被缓冲的输出流将数据写入缓冲区,只有在缓冲区满的时候才调用本机输出API。
程序可以使用我们已经用过几次的包装习惯把未缓冲的流转换成已缓冲的流,即将未缓冲的流对象传给已缓冲的流类的构造器。以下是如何修改
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
andBufferedOutputStream
create buffered byte streams, whileBufferedReader
andBufferedWriter
create buffered character streams.译:
有四种已缓冲流的类用来包装未缓冲的流:
BufferedInputStream
和BufferedOutputStream
创建已缓冲的字节流;BufferedReader
和BufferedWriter
创建已缓冲的字符流。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 ofprintln
orformat
. See Formatting for more on these methods.To flush a stream manually, invoke its
flush
method. Theflush
method is valid on any output stream, but has no effect unless the stream is buffered.译:刷新缓冲流
在关键时间点写出缓冲区,而不必等待缓冲区满,通常是有意义的。这被称为刷新缓冲区。
一些已缓冲输出类支持自动刷新,由一个可选的构造器参数指定。当启用自动刷新时,某些关键事件会导致刷新缓冲区。例如,自动刷新
PrintWriter
对象在每次调用println
或format
的时候刷新缓冲区。查看Formatting 获取更多这些方法。若要手动刷新流,可以调用其
flush
方法。flush
方法对任何输出流都有效,但除非对流进行缓冲,否则不起作用。