IO流-字节流

本文详细介绍了Java中的IO流,包括字节流的使用(如创建、写入、追加和读取),以及FileInputStream和FileOutputStream的基本操作。此外,还探讨了如何通过BufferedStream提高文件拷贝的效率。
摘要由CSDN通过智能技术生成

IO流-字节流

IO流-体系结构

在这里插入图片描述
在这里插入图片描述
细节

      输出流关联文件,文件如果不存在:会自动创建出来
            如果文件存在:会清空现有的内容,然后再进行写入操作
        /*
        细节:
            输出流关联文件,文件如果不存在:会自动创建出来
                如果文件存在:会清空现有的内容,然后再进行写入操作
         */
        //创建字节输出流对象,关联文件
        FileOutputStream fos = new FileOutputStream("D:\\file_io\\A.txt");
        //写出数据 一个字节
        fos.write(97);  //a
        //字节数组
        byte[] bys = {98,99,100};
        fos.write(bys);
        //字符串可以用getBytes方法
        fos.write("你好".getBytes());

开启追加写入模式,在后面加个true

        FileOutputStream fos = new FileOutputStream("D:\\file_io\\A.txt",true);

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

        FileInputStream fis = new FileInputStream("D:\\file_io/A.txt");
        int read;
        while ((read=fis.read())!=-1){
            System.out.println((char) read);
        }
        fis.close();

在这里插入图片描述

        FileInputStream fis = new FileInputStream("D:\\file_io/A.txt");
        byte[] bytes = new byte[2];
        int length;
        while ((length=fis.read(bytes))!=-1){
            String s= new String(bytes,0,length);
            System.out.println(s);
        }
        fis.close();

在这里插入图片描述
文件拷贝:

public class BufferedStreamDemo1 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\file_io/A.txt");
        //1.创建字节缓冲输入流
        BufferedInputStream bis = new BufferedInputStream(fis);
        //2.创建字节缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\file_io/test.txt"));

        //3.读写操作
        int i;
        while ((i=bis.read())!=-1){
            bos.write(i);
        }

        //4.关流
        bis.close();
        bos.close();
    }
}

拷贝的效率测试(下图为缓冲流+自定义数组拷贝原理图):
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值