Java——字节流简单介绍

/*
字节输出流 OutputStream:
字节输入流 InputStream:

*/
import java.io.*;
class test{
    public static void main(String[] args)throws IOException{
        //writeFile();
        //readFile1();
        //readFile2();
        readFile3();
    }

    public static void readFile3()throws IOException{
        FileInputStream fis = new FileInputStream("temp.txt");
        int num = fis.available();//返回文件的总大小,单位是字节,文件太大时不适合,数组要开辟内存,太大会溢出
        byte[] arr = new byte[num];

        int len = fis.read(arr);
        System.out.print(new String(arr,0,len));

        fis.close();

    }

    public static void readFile2()throws IOException{
        FileInputStream fis = new FileInputStream("temp.txt");
        byte[] arr = new byte[1024];
        int num;
        while((num = fis.read(arr))!=-1){
            System.out.print(new String(arr,0,num));
        }
        fis.close();
    }

    //使用字节输入流从文件中读取数据
    public static void readFile1()throws IOException{
        FileInputStream fis = new FileInputStream("temp.txt");

        //一次读一个字节
        int num;
        while((num = fis.read())!=-1){
            System.out.print((char)num);
        }
        fis.close();
    }

    //使用字节输出流向文件中写入数据
    public static void writeFile()throws IOException{
        //创建字节输出流对象和文件相关联
        FileOutputStream fos = new FileOutputStream("temp.txt");

        //直接写入文件,不需要flush
        fos.write("abcde".getBytes());//[97,98,99,100,101]

        fos.close();
    }
}
经验分享 程序员 微信小程序 职场和发展