IO流之文件拷贝

IO流之文件拷贝

实例

public class FileCopy {
    public static void main(String[] args) {
        //完成文件拷贝,将d:\\pic.jpg 拷贝到 e:\\
        /**
         * 思路分析
         * 1.创建文件的输入流,将文件读入到程序
         * 2.创建文件的输出流,将读取到的文件数据,写入到指定的文件
         */
        String srcFilePath = "d:\\pic.jpg";
        String destFilePath = "e:\\picCopy.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效率
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1) {
                //读取到后,就写入到文件,通过fileOutputStream
                //即边读边写
                fileOutputStream.write(buf,0,readLen);
            }
            System.out.println("拷贝完成~");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭输入流和输出流,释放资源
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
posted on 2023-01-13 20:36  小宇不会编程  阅读(17)  评论(0)    收藏  举报