原文链接
原文:
Byte Streams
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.
There are many byte stream classes. To demonstrate how byte streams work, we’ll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.
Using Byte Streams
We’ll explore FileInputStream and FileOutputStream by examining an example program named CopyBytes, which uses byte streams to copy xanadu.txt, one byte at a time.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
CopyBytes spends most of its time in a simple loop that reads the input stream and writes the output stream, one byte at a time, as shown in the following figure.
Simple byte stream input and output.
Simple byte stream input and output.
Always Close Streams
Closing a stream when it’s no longer needed is very important — so important that CopyBytes uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.
One possible error is that CopyBytes was unable to open one or both files. When that happens, the stream variable corresponding to the file never changes from its initial null value. That’s why CopyBytes makes sure that each stream variable contains an object reference before invoking close.
When Not to Use Byte Streams
CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams, as discussed in the next section. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.
So why talk about byte streams? Because all other stream types are built on byte streams.
译文:
字节流
程序使用字节流执行8位的字节输入和输出。所有的字节流类都是来自输入流和输出流。
有很多的字节流类存在。为了展示字节流是怎么工作的,我们来重点讨论文件的输入输出字节流,文件输入流以和文件输出流。其他类型的字节流也经常用在相同的地方,他们主要在构造上和文件输入输出流不同。
使用字节流
我们将使用一个名叫复制字节的示例程序来研究文件输入流和文件输出流,
它使用了字节流来复制xanadu.txt文件,一次复制一个字节。
复制字节这个程序花了很大一部分时间在一个简单的读取输入流和写入输出流的循环上,一个字节一次,正如下图所示。
总是会关闭流
当一个流不使用时关闭它是很重要的,复制字节这个程序使用了一个finally语句块来保证流在不用时,甚至发生错误时会关闭。这种做法有利于避免严重的资源泄露。
这个程序有个错误可能是不能打开一个或者两个文件,当这种情况发生时,文件相对应的流变量不会改变它最初的空值。这就是为什么这个程序在调用关闭之前要确保每个流变量包含了一个对象参数。
当没有使用字节流时
这个程序看上去像一个普通的程序,但是它实际上代表了一种你应该避免的低级输入输出。因为xanadu.txt包含了字符数据,最好的方法是使用字符流,下一章我们会讨论到它。还有很多与那些复杂的数据类型有关的流。字节流应该只在最原始的输入输出时用上。
所以为什么我们要讨论字节流?因为其他所有形式的流都是在字节流的接触上建立起来的。