IO流之使用文件字节输入输出流完成文件Copy

package cn.hq.io;

import java.io.*;

/**
 * 文件拷贝:文件字节输入流、输出流
 *
 * @author HQ
 * @Date 2018/12/11
 */
public class Copy {
    public static void main(String[] args) {
        copy("123.txt", "123copy.txt");
    }

    public static void copy(String srcPath, String destPath) {
        //1.创建源
        File src = new File(srcPath);//源头
        File dest = new File(destPath);//目的地
        //2.选择流
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //3.操作(写出)
            inputStream = new FileInputStream(src);
            outputStream = new FileOutputStream(dest);
            byte[] flush = new byte[1024];//缓冲容器
            int length = -1;//接受长度
            while ((length = inputStream.read(flush)) != -1) {
                outputStream.write(flush, 0, length);//字符串-->字节数组(编码)
            }
            outputStream.flush();//刷新
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.释放资源 先打开的后关闭
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

发布了12 篇原创文章 · 获赞 4 · 访问量 1750

猜你喜欢

转载自blog.csdn.net/Cymothoe/article/details/84958202