• 技术文章 >Java >java教程

    Java中使用IO流复制文件的方法实例解析

    PHPzPHPz2023-04-24 12:40:07转载21

    1、使用FileInputStream、FileOutputStream完成文件的复制

        public void fileCapy(String src, String dest) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
     
            try {
                fis = new FileInputStream(new File(src));
                fos = new FileOutputStream(new File(dest));
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) != -1) {
                    fos.write(bytes, 0, length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    2、使用FileReader、 FileWriter完成文本的复制(对于非文本文件, 只能使用字节流)

        public void textCapy(String src, String dest) {
            FileReader fr = null;
            FileWriter fw = null;
     
            try {
                fr = new FileReader(new File(src));
                fw = new FileWriter(new File(dest));
                char[] chars = new char[1024];
                int length;
                while ((length = fr.read(chars)) != -1) {
                    fw.write(chars, 0, length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fw != null) {
                    try {
                        fw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
     
                if (fr != null) {
                    try {
                        fr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    以上就是Java中使用IO流复制文件的方法实例解析的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
    专题推荐:Java io
    上一篇:Java线程常用的操作有哪些? 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 如何避免JAVA中简单的for循环出现异常?• java怎么随机打乱数组顺序• Java如何使用Freemarker实现页面静态化?• Java中如何使用数组?• 如何在Java中将二维数组转换为一维数组
    1/1

    PHP中文网