2018-11-19

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.

package com.feng.learnjava; 
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 {
                //必须把文件放在项目根目录,否则报 IO 异常
                    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();
                        }
                }
        }
}
  • int java.io.FileInputStream.read() throws IOException
    Reads a byte of data from this input stream. This method blocks if no input is yet available.

  • void java.io.FileOutputStream.write(int b) throws IOException
    Writes the specified byte to this file output stream. Implements the write method of OutputStream.

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.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容