IO字节流和字节缓冲流

package com.播客;

import java.io.*;

public class FileIOStreamDome {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
//method1(); //耗时:55596毫秒 字节流一次读取一个字节
//method2(); //耗时:97毫秒 字节流一次读取一个字节数组
//method3(); //耗时:552毫秒 字节缓冲流一次只读写一个字节
//method4(); //耗时:33毫秒 字节缓冲流一次只读写一个字节数组
long end = System.currentTimeMillis();
System.out.println(“耗时:” + (end - start) + “毫秒”);
}

//字节缓冲流一次只读写一个字节数组
private static void method4() throws IOException {
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("路径可绝对也可相对"));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("路径可绝对也可相对"));
    byte[] bys = new byte[1024];
    int len;
    while ((len = bis.read(bys)) != -1) {
        bos.write(bys, 0, len);
    }
    //释放资源
    bis.close();
    bos.close();
}

//字节缓冲流一次只读写一个字节
private static void method3() throws IOException {
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("路径可绝对也可相对"));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("路径可绝对也可相对"));
    int by;
    while ((by = bis.read()) != -1) {
        bos.write(by);
    }
    //释放资源
    bis.close();
    bos.close();
}

//字节流一次读取一个字节数组
private static void method2() throws IOException {
    FileInputStream fis = new FileInputStream("路径可绝对也可相对");//目标源地址
    FileOutputStream fos = new FileOutputStream("路径可绝对也可相对");//目的地地址
    byte[] bys = new byte[1024];//1024及其整数倍
    int len;
    while ((len = fis.read(bys)) != -1) {//把读取到的数据赋值给by;判断读取到的数据是否是-1
        fos.write(bys, 0, len);
    }
    //释放资源
    fis.close();
    fos.close();
}

//字节流一次只读写一个字节
private static void method1() throws IOException {
    FileInputStream fis = new FileInputStream("路径可绝对也可相对");//目标源地址
    FileOutputStream fos = new FileOutputStream("路径可绝对也可相对");//目的地地址
    int by;
    while ((by = fis.read()) != -1) {//把读取到的数据赋值给by;判断读取到的数据是否是-1
        fos.write(by);
    }
    //释放资源
    fis.close();
    fos.close();
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值