字节流数据的写出(输出)和读取(输入)

写出数据 FileOutputStream

FileOutputStream out = new FileOutputStream("E:\\a.txt");
//写出字符串"abc"
//字节流没有缓冲区
out.write("abc".getBytes());
//关流,释放文件
out.close();

读取数据 FileInputStream

import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
  FileInputStream in = new FileInputStream("E:\\a.txt");
        //数据的读取没有缓冲区,需要手动提供一个缓冲区
     //设置为每次存储10个字符
        byte[] b = new byte[10];
        //定义一个变量用来记录每次读取到的字符个数,给变量len赋初值(可以是任意值)
        //防止read读取数据失败导致报错
        int len  = -1;
        //该read的返回值表示这一次读取到的字符的个数
        while((len = in.read(b)) != -1){
            System.out.println(new String(b, 0, len));
        }
        in.close();
    }
}

猜你喜欢

转载自www.cnblogs.com/lj-cn/p/9374359.html