java InputStream和OutputStream的简单理解

package cn.itcast.chapter07.example05;
import java.io.*;
/**
 * 文件的拷贝(使用缓冲区拷贝文件)
 */
public class Example05 {
    public static void main(String[] args) throws Exception {
        //这个过程就像倒水一样,首先定义两条水管in和out,他们都是单向的:
        //  内存  <-----------in-----------  文件(source\\五环之歌.mp3)
        //  内存  -----------out---------->  文件(target\\五环之歌2.mp3)
        //in.read()就像把大池子(源文件(source\\五环之歌.mp3))里的水分批倒入水桶(buff数组),
        //至于分批几次则是取决于水桶(buff数组)的大小。
        //对应地,out.write()则是将水桶里的水倒入另一个大池子(目标文件(target\\五环之歌2.mp3)),
        //这时,可以有意的选取我们小水桶中的一部分(通过参数(byte[] b(我们的小水桶), int off(起始索引), int len(总长度)))
        InputStream in=new FileInputStream("source\\五环之歌.mp3");
        OutputStream out=new FileOutputStream("target\\五环之歌2.mp3");
        byte[] buff=new byte[1024];
        int len,n=0;
        long begintime=System.currentTimeMillis();
        while((len=in.read(buff))!=-1) {//将文件分成x个部分,每个部分字节长1024
            System.out.println(len);
            n=n+1;
            out.write(buff,0,len);
        }
        long endtime=System.currentTimeMillis();
        System.out.println(n+"  消耗时间:"+(endtime-begintime)+"毫秒");
        in.close();
        out.close();
//        // 创建一个字节输入流,用于读取当前目录下source文件夹中的mp3文件
//        InputStream in = new FileInputStream("source\\五环之歌.mp3");
//        // 创建一个文件字节输出流,用于将读取的数据写入当前目录的target文件中
//        OutputStream out = new FileOutputStream("target\\五环之歌.mp3");
//        // 以下是用缓冲区读写文件
//        byte[] buff = new byte[1024]; // 定义一个字节数组,作为缓冲区
//        // 定义一个int类型的变量len记住读取读入缓冲区的字节数
//        int len;
//        long begintime = System.currentTimeMillis();
//        while ((len = in.read(buff)) != -1) { // 判断是否读到文件末尾
//            out.write(buff, 0, len); // 从第一个字节开始,向文件写入len个字节
//        }
//        long endtime = System.currentTimeMillis();
//        System.out.println("拷贝文件所消耗的时间是:" + (endtime - begintime) + "毫秒");
//        in.close();
//        out.close();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值