IO字节缓冲流

目录

字节流:

直接缓冲流:

拷贝文件的四种方式有那些?

下面是拷贝文件的代码实现:


字节流:

  • 可以操作(拷贝)所有类型的文件
  • 字节输入流:FileInputStream
  • 字节输出流:FileOutputStream

直接缓冲流:

  • 可以提高效率
  • 不能直接操作文件,需要传递字节流
  • 字节缓冲输入流:BufferedInputStream
  • 字节缓冲输出流:BufferedOutputStream

拷贝文件的四种方式有那些?

  1. 字节流一次读写一个字节
  2. 字节流一次读写一个字节数组
  3. 字节缓冲流一次操作一个字节
  4. 字节缓冲流一次操作一个字节数组

下面是拷贝文件的代码实现:



import java.io.*;

public class InputOutput{
    public static void main(String[] args) throws IOException {
        //单字节拷贝
        FileInputStream fis = new FileInputStream("day10\\src\\com\\wt\\homework\\HomeWork.txt");
        FileOutputStream fos = new FileOutputStream("day10\\src\\com\\wt\\homework\\HomeWorkCopy.txt");

        //copy1(fis, fos);//字节流单字节拷贝
        //copy2(fis, fos);//字节流数组拷贝

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("day10\\src\\com\\wt\\homework\\HomeWork.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day10\\src\\com\\wt\\homework\\HomeWorkCopyHuanchong.txt"));
        //copy3(bis,bos);//缓冲流单字节拷贝
        //copy4(bis, bos);//缓冲流数组拷贝
    }

    /**
     * 缓冲流数组拷贝
     * @param bis
     * @param bos
     * @throws IOException
     */
    private static void copy4(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
        byte[] bytes = new byte[1024];
        int len;
        while ((len= bis.read(bytes))!= -1){
            bos.write(bytes,0,len);
        }
        bis.close();
        bos.close();
    }

    /**
     * 缓冲流单字节拷贝
     * @param bis
     * @param bos
     * @throws IOException
     */
    private static void copy3(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
        int b ;
        while ((b= bis.read())!=-1){
            bos.write(b);
        }
        bis.close();
        bos.close();
    }

    /**
     * 字节流数组拷贝
     * @param fis
     * @param fos
     * @throws IOException
     */
    private static void copy2(FileInputStream fis, FileOutputStream fos) throws IOException {
        byte[] bytes = new byte[1024];
        int len;
        while ((len= fis.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        fis.close();
        fos.close();
    }

    /**
     * 字节流单字节拷贝
     * @param fis
     * @param fos
     * @throws IOException
     */
    private static void copy1(FileInputStream fis, FileOutputStream fos) throws IOException {
        int b;
        while((b = fis.read())!=-1){
            fos.write(b);
        }
        fis.close();
        fos.close();
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉锵T

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值