使用字节缓存流复制文件和图片 (对IO的基本应用)

package com.xiaocheng.io;

import java.io.*;

/**
 * 对IO的基本应用
 * 使用字节缓存流copy文件
 */
public class InputOutputStreamCopyTest {
    public static void main(String[] args) {
        copyFile("d:/1.png","d:/2.png");
    }

    /**
     * 将src文件的内容拷贝到dest文件中
     * @param src 源文件
     * @param dest 目标文件
     */
    static void copyFile(String src,String dest){
        //流的声明
//        long l1 = System.currentTimeMillis();
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            //流的初始化
            bos = new BufferedOutputStream(new FileOutputStream(dest));
            bis = new BufferedInputStream(new FileInputStream(src));

            int temp = 0;
            while ((temp = bis.read())!=-1){
                bos.write(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(bos!=null){
                    bos.close();
                }
                if (bis!=null){
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        long l2 = System.currentTimeMillis();
//        System.out.println(l2 - l1);
    }
}
posted @ 2021-04-13 20:23  愿半生代码如一生好友  阅读(84)  评论(0)    收藏  举报