欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java 文件复制,

来源: javaer 分享于  点击 31807 次 点评:60

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("关闭流失败!");
                }
            }
        }
    }
}

 

相关文章

    暂无相关文章
相关栏目:

用户点评