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

2017-07-13  本文已影响0人  youyuge

收纳进此专辑: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.

二、字节流的使用

我们使用如下类,在俩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.

简单字节流的输入输出

三、请记得关闭流

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.

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

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.

上一篇 下一篇

猜你喜欢

热点阅读