InputStream

一次性读取一个字节

package com.iopractise;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 读一个字节,就打印一个字节
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        //1.创建FileInputStream,并指定文件路径
        FileInputStream fileInputStream = new FileInputStream("d:\aaa.txt");
        //2.读取文件
        int data=0;
        while ((data=fileInputStream.read())!=-1){
            System.out.print((char) data);//如果不加类型转化的话,只会的到字符所对应的ascii码值。
        }
        //3.关闭
        fileInputStream.close();
        System.out.println();
        System.out.println("执行完毕");
    }
}

运行结果:

abcdefg

执行完毕

一次性读取多个字节

package com.iopractise;


import java.io.FileInputStream;
import java.io.IOException;

/**
 * 一次性读取多个字节
 */
public class Demo02 {
    public static void main(String[] args) throws IOException {
        //1.创建FileInputStream,并指定文件路径
        FileInputStream fileInputStream = new FileInputStream("d:\aaa.txt");
        //2.读取文件
        byte[] buffer = new byte[3];//表示一次性读取多个字节 这里我们一般写的是1024字节,表示一次读取1K
        int count=0;
        while ((count=fileInputStream.read(buffer))!=-1){
            System.out.println(new String(buffer, 0, count));
        }
        //3.关闭
        fileInputStream.close();
        System.out.println("执行完毕");
    }
}

  

运行结果:

abc

def

g

执行完毕

原文地址:https://www.cnblogs.com/dongyaotou/p/14383537.html