使用字节流来复制文件

复制文件的雏形

public class MyTest2 {
public static void main(String[] args) throws IOException {
    //采用读取一个字节,写入一个字节的方式,复制mp3文件
    FileInputStream in = new FileInputStream("D:\\夜夜夜夜.mp3");
    FileOutputStream out = new FileOutputStream("E:\\夜夜夜夜.mp3");
    //int read = in.read();
    //out.write(read);
    int len = 0;
    while ((len = in.read()) != -1) {
        out.write(len);
    }
    in.close();
    out.close();
}
}

发现问题进行优化:

很显然,一次读取一个字节,写一个字节,复制文件太耗时了,所以不推荐使用,我们推荐一次读取一个字节数组,写入一个字节数组。

public class MyTest3 {
public static void main(String[] args) throws IOException {
    FileInputStream in = new FileInputStream("D:\\夜夜夜夜.mp3");
    FileOutputStream out = new FileOutputStream("E:\\夜夜夜夜.mp3");
    //创建一个字节数组,充当缓冲区
    byte[] bytes = new byte[1024 * 8];
    //定义一个变量,记录每次读取到的有效字节个数
    int len = 0;
    while ((len = in.read(bytes)) != -1) {
        out.write(bytes, 0, len);
    }
    in.close();
    out.close();
}
}

进一步优化:

我们采用高效的字节流进行操作

public class MyTest {
public static void main(String[] args) throws IOException {
    //高效的字节输入输出流
    // BufferedInputStream
    // BufferedOutputStream
    // "D:\\夜夜夜夜.mp3"

    //BufferedInputStream(InputStream in, int size)
    //创建具有指定缓冲区大小的 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。
    long start = System.currentTimeMillis();
    //copyFile();
    copyFile2();
    long end = System.currentTimeMillis();
    System.out.println("耗时" + (end - start) + "毫秒");
}

private static void copyFile2() throws IOException {
    FileInputStream in = new FileInputStream("D:\\夜夜夜夜.mp3");
    FileOutputStream out = new FileOutputStream("E:\\夜夜夜夜.mp3");
    int len2 = 0;
    byte[] bytes = new byte[1024 * 10];
    while ((len2 = in.read(bytes)) != -1) {
        out.write(bytes, 0, len2);
    }
    in.close();
    out.close();
}

private static void copyFile() throws IOException {
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\夜夜夜夜.mp3"), 1024 * 10);
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\夜夜夜夜.mp3"), 1024 * 10);
    int len2 = 0;
    byte[] bytes = new byte[1024 * 10];
    while ((len2 = bis.read(bytes)) != -1) {
        bos.write(bytes, 0, len2);
    }
    bis.close();
    bos.close();
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值