package com.sf._03_字节输入流;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class Test {
    /**
     * 字节输入流:
     * 把磁盘当中文件内容读取到程序中
     *
     * 1 创建字节输入流
     * 2 read(字节)  read(字节数组)
     * 3 关闭资源
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // 1 创建出来字节输入流
        FileInputStream fileInputStream = new FileInputStream(new File("D:\\a.txt"));
        // 2 读取内容
        /**
         * 每次调用read 都可以读取一个字节
         * 如果读取不到了就是-1
         */
//        System.out.println(fileInputStream.read());
//        System.out.println(fileInputStream.read());
//        System.out.println(fileInputStream.read());
//        System.out.println(fileInputStream.read());
//        System.out.println(fileInputStream.read());
//        System.out.println(fileInputStream.read());
//        System.out.println(fileInputStream.read());

        byte[] buffer = new byte[2];
        /**
         * 单纯就调用read()  返回值就是你读取那个字节内容
         * 比如你读取a 字节返回值  97   你读去b 返回就是98
         *
         * 如果你调用read(byte[])  返回值你读取字节长度
         */
        // a b
        System.out.println(fileInputStream.read(buffer)); //2
        System.out.println(Arrays.toString(buffer));
        System.out.println(new String(buffer));
        //c e
        System.out.println(fileInputStream.read(buffer)); //2
        System.out.println(Arrays.toString(buffer));
        System.out.println(new String(buffer));
        //d a
        System.out.println(fileInputStream.read(buffer)); //2
        System.out.println(Arrays.toString(buffer));
        System.out.println(new String(buffer));
        // a
        int readLen = fileInputStream.read(buffer);
        // readLen = 1
        System.out.println(fileInputStream.read(buffer)); //1
        // [97,97]  我们读取真实长度其实就只有前面这个97  后面97 是他jdk 给填充的是无效的
        System.out.println(Arrays.toString(buffer));
        System.out.println(new String(buffer,0,readLen));
        //
        System.out.println(fileInputStream.read(buffer)); //-1
        // [97,97]
        System.out.println(Arrays.toString(buffer));
        System.out.println(new String(buffer,0,readLen));

        // 3 关闭资源
        fileInputStream.close();
    }
}
