Java中IO流复制文件的方法实例分析

本篇内容主要讲解“Java中IO流复制文件方法实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java中IO流复制文件方法实例分析”吧!

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流复制文件方法实例分析”有了更深的了解,不妨来实际操作一番吧!这里是编程之家网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...