java基础--流读写文件(由浅入深)

1指定每次读2个字节

 FileInputStream  fis = new FileInputStream("c.txt");
        int length;
        byte[] bytes=new byte[2];
        while ((length=fis.read(bytes))!=-1){
            System.out.println("bytes = " + new String(bytes,0,length));
        }
        fis.close();

日志:

bytes = df
bytes = 6y
bytes = y6
bytes = 56

2 读写文件

		 System.out.println("start = " + new Date().toLocaleString());
		FileInputStream  fis = new FileInputStream("c.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("c1.txt");
        int length;
        byte[] bytes=new byte[2];
        while ((length=fis.read(bytes))!=-1){
            System.out.println("bytes = " + new String(bytes,0,length));
            System.out.println("toLocaleString = " + new Date().toLocaleString());
            fileOutputStream.write(bytes,0,length);
        }
        fis.close();
        fileOutputStream.close();
        System.out.println("end = " + new Date().toLocaleString());
700M文件
start = 2021年7月4日上午10:55:44
end = 2021年7月4日上午10:55:49

3缓冲流读写文件(默认自建缓冲区)

 BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("c.txt"));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("c2.txt"));
        int length;
        while ((length=bufferedInputStream.read())!=-1){
            System.out.println("length = " + length);
            bufferedOutputStream.write(length);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
700M文件
start = 2021年7月4日上午10:50:29
end = 2021年7月4日上午10:50:51

4缓冲流+数组读写文件

BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("c.txt"));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("c3.txt"));
        int length;
        byte[] bytes = new byte[1024];
        while ((length=bufferedInputStream.read(bytes))!=-1){
            System.out.println("length = " + new String(bytes,0,length));
            bufferedOutputStream.write(bytes,0,length);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
700M文件
1S

总结:
当缓存数组都设为1024时,读写700M文件基础流FileInputStream耗时4秒,高级缓存流BufferInputStream耗时1秒;然而byte数组设为10*1024时,基础流和缓存流耗时均为1秒。可见读写文件的效率主要取决于数组byte设定的大小,而与流的高级与否关系不大。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值