Java基础进阶IO流-文件复制

导读:本篇文章讲解 Java基础进阶IO流-文件复制,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

使用字节流文件复制

public class CopyTest01 {
    public static void main(String[] args) {

        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream("C:\\Users\\王一林\\Desktop\\论文pdf\\2122_41_13500_080902_3118070108_BS_001.pdf");
            fos = new FileOutputStream("D:\\2122_41_13500_080902_3118070108_BS_001.pdf");

            //先读,每次读1M数据(1024 * 1024)// 最核心的:一边读,一边写
            byte[] bytes = new byte[1024 * 1024];
            int readCount = 0;
            while((readCount = fis.read(bytes)) != -1){
                //读多少,就写多少API
                fos.write(bytes,0,readCount);
            }

            //最后输出流一定要刷新
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //这里要分开try,因为如果一起try的话,如果其中一个流出现异常会影响到另一个流的关闭。
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

复制结果

在这里插入图片描述

使用FileReader FileWriter字符流进行拷贝的话,只能拷贝“普通文本”文件。(.java文件也是普通文本文件)

public class Copy02Test01 {
    public static void main(String[] args) {
        FileReader in = null;
        FileWriter out = null;
        try {
            in = new FileReader("IO\\src\\com\\newstudy\\javase\\io\\Copy02Test01.java");
            out = new FileWriter("Copy02Test01.java");
            //读,每次读1MB
            char[] chars = new char[1024 * 512];//1MB
            int readCount = 0;
            //一边读,一边写
            while((readCount = in.read(chars)) != -1){
                //写
                out.write(chars,0,readCount);
            }
            //刷新
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

复制结果:在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/94256.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!