Java开罐头——I/O流官方指南之字节流Byte Streams

收纳进此专辑:I/O流官方中文指南系列概述及索引

大部分内容来自 The Java™ Tutorials 官方指南,其余来自别处如ifeve的译文、imooc、书籍Android面试宝典等等。
作者: @youyuge
个人博客站点: https://youyuge.cn

一、字节流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.

  • 我们的Java程序使用字节流来输入输出8比特(bit)的字节。所有的字节流的类都继承自InputStream和OutputStream。
  • 有很多字节流的类。为了说明字节流如何工作,我们将关注文件的I/O字节流FileInputStream 和 FileOutputStream。其他种类的字节流大部分使用上类似,只是在内部构造的方式上不同。

二、字节流的使用

我们使用如下类,在俩txt之间进行复制,一次复制一个字节byte。

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.

  • 复制字节在读取输入流和写输出流上这个简单的循环上花费了最多的时间,一次复制一个字节(可用别的方法一次多个)。如下图所示:
Java开罐头——I/O流官方指南之字节流Byte Streams_第1张图片
简单字节流的输入输出

三、请记得关闭流

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.

  • 及时关闭不再需要的流非常重要,防止内存泄漏。用finally语句块确保流一定会被关闭,哪怕中间出错了。

四、什么时候不使用字节流

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.

  • 上面那种方式的复制字节是低级的I/O方式,我们应该避免使用。既然txt中包含的是字符数据,最好的方法是使用字符流charater streams。字节流是最原始的I/O方式。

So why talk about byte streams? Because all other stream types are built on byte streams.

  • 既然如此我们为何要讨论字节流?因为别的形式的流类型是在字节流的基础上构建的。

你可能感兴趣的:(Java开罐头——I/O流官方指南之字节流Byte Streams)