收纳进此专辑:I/O流官方中文指南系列概述及索引
大部分内容来自 The Java™ Tutorials 官方指南,其余来自别处如ifeve的译文、imooc、书籍Android面试宝典等等。
作者: @youyuge
个人博客站点: https://youyuge.cn
一、缓冲流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.
目前为止,我们所使用的都是未缓冲的I/O。这意味着每次的读写请求都直接通过底层的操作系统OS。这可能使得一个程序不那么有效率,由于每次这样的请求会经常触发硬盘的读取,网络活动或者一些其他相当耗时的操作。
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.
为了减少这种负载,Java平台实现了缓冲I/O流。缓冲输入流从一个被称为缓冲区的存储区读取数据;仅仅当缓冲区为空时,才会调用底层(native层)的输入的api方法。同样,缓冲输出流输出数据到缓冲区,仅当缓冲区满了之后才会调用底层的输出方法(或者直接调用flush方法立刻输出缓冲区内容)。
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:
Java程序能通过包装构造方法,把一个非缓冲流转换成缓冲流。只要将非缓冲流对象传给缓冲流的类的构造器即可。下面展示了如何通过构造器包装来使用缓冲流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, while BufferedReader
and BufferedWriter
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 of println
or format
. See Formatting for more on these methods.
一些缓冲输出类支持自动清空缓冲区,由可选的构造器参数来确定。当自动清空可用时,一些明确规定好的关键事件会触发缓冲区的清空。举个栗子,一个自动清空的PrintWriter对象在每次调用println或者format方法时会自动清空输出缓冲区。(比如我们熟知的System.out.println()方法)
To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.
想人为地清空一个流,可以调用它的flush()方法。这个方法在任何的输出流上都是可用的,但是仅仅在缓冲流上有效果。
网友评论