[Java 12 IO] InputStream 继承自 它 的类,都是向 程序中 输入数据

InputStream 继承自 它 的类,都是向 程序中 输入数据
package com.qunar.basicJava.javase.io;

import java.io.*;

/**
 * Author: libin.chen@qunar.com  Date: 14-6-5 16:10
 */
public class InputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        // 第 1 步 : 使用 File 类找到一个文件
        File file = new File("/home/hp/tmp/test.txt");
        // 第 2 步 : 通过子类实例化父类对象
        InputStream inputStream = new FileInputStream(file);
        // 第 3 步 : 进行读操作
        byte b[] = new byte[(int) file.length()];
        inputStream.read(b);

        // 循环读
        InputStream inputStream1 = new FileInputStream(file);
        byte b2[] = new byte[(int) file.length()];
        for (int i = 0; i < b.length; i++) {
            b2[i] = (byte)inputStream1.read();
        }

        // 另一种方式读
        InputStream inputStream2 = new FileInputStream(file);
        byte b3[] = new byte[1024];
        int len = 0;
        int temp = 0;
        while ((temp = inputStream2.read()) != -1) { // 如果 temp 的值不是 -1, 则表示文件没有被读完
            b3[len++] = (byte)temp;
        }

        // 第 4 步 : 关闭输出流
        inputStream.close();
        inputStream1.close();
        inputStream2.close();

        System.out.println(new String(b));

        System.out.println("b2 : " + new String(b2));

        System.out.print("b3 : ");
        System.out.println(new String(b3, 0, len));
    }
}

原文地址:https://www.cnblogs.com/robbychan/p/3786494.html