java 文件复制

2020-04-10 16:08:32来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

java 文件复制

public class CopyText {
    public static void main(String[] args) {
        copy_1();
    }

    public static void copy_1() {
        FileWriter fw = null;
        FileReader fr = null;
        try {
            fw = new FileWriter("demo_desc.txt");
            //与已有文件关联
            fr = new FileReader("demo_src.txt");
            int ch = 0;
            while ((ch = fr.read()) != -1) {
                fw.write(ch);
            }
        } catch (IOException e) {
            throw new RuntimeException("读写失败!");
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流失败!");
                }
            }
            if (fw != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流失败!");
                }
            }
        }
    }

    public static void copy_2() {
        FileWriter fw = null;
        FileReader fr = null;
        try {
            fw = new FileWriter("demo_desc.txt");
            //与已有文件关联
            fr = new FileReader("demo_src.txt");
            char[] buf = new char[1024];
            int num = 0;
            while ((num = fr.read(buf)) != -1) {
                fw.write(buf, 0, num);
            }
        } catch (IOException e) {
            throw new RuntimeException("读写失败!");
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流失败!");
                }
            }
            if (fw != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流失败!");
                }
            }
        }
    }
}

 


原文链接:https://www.cnblogs.com/hongxiao2020/p/12676618.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:G1垃圾回收器

下一篇:java 文本读取