Java字节流实现--文件与目录的拷贝

一、文件的拷贝–>原始方法

注意:若使用InputStream将全部要拷贝的内容直接读取到程序里面,在文件很大时,将会导致程序直接卡死,所以强烈不推荐一次性全部拷贝

所以我们采用部分拷贝,利用字节数组读取一部分存入字节数组,再将该部分输出。再利用while循环以此往复,直到全部拷贝过来
代码如下:

import java.io.*;

class FileUntil {//定义一个文件操作工具类
    private File srcFile;//原路径
    private File desFile;//目标路径

    public FileUntil(String src, String des) {
        this(new File(src), new File(des));
    }

    public FileUntil(File srcFile, File desFile) {
        this.srcFile = srcFile;
        this.desFile = desFile;
    }

    public boolean copy() throws Exception {  //文件拷贝处理

        if (!this.srcFile.exists()) {  //文件必须存在
            System.out.println("要拷贝的源文件不存在!");
            return false;
        }
        if (!this.desFile.getParentFile().exists()) {
            this.desFile.getParentFile().mkdirs();  //如果父目录不存在就创建父目录
        }

        byte data[] = new byte[1024];//开辟一个拷贝的缓冲区
        InputStream input = null;
        OutputStream output = null;

        try {
            input = new FileInputStream(this.srcFile);
            output = new FileOutputStream(this.desFile);
            int len = 0;//当len=-1的时候拷贝完成
            while ((len = input.read(data)) != -1) {
                output.write(data, 0, len);
            }
            return true;
        } catch (Exception e) {//异常类型太多,所以用Exception
            throw e;
        } finally {  //无论出不出错都要关闭
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }
}

public class fille {
    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();//用来计时耗时,开始时间

        FileUntil fu = new FileUntil("d:\\123.txt", "d:\\456\\789.txt");
        System.out.println(fu.copy() ? "拷贝成功" : "拷贝失败");//返回true就是拷贝成功,返回false就是拷贝失败

        long end = System.currentTimeMillis();//结束时间
        System.out.println("拷贝用时:" + (end - start));
    }
}

二、文件的拷贝–>transferTo

JDK1.9之后InputStream和Reader类都追加有数据转存的处理操作方法,其他部分都与原始方法大致相同,但可以省略while循环与字节数组
代码如下:注释掉的代码块即为被取代部分

import java.io.*;

class FileUntil {//定义一个文件操作工具类
    private File srcFile;//原路径
    private File desFile;//目标路径

    public FileUntil(String src, String des) {
        this(new File(src), new File(des));
    }

    public FileUntil(File srcFile, File desFile) {
        this.srcFile = srcFile;
        this.desFile = desFile;
    }

    public boolean copy() throws Exception {  //文件拷贝处理

        if (!this.srcFile.exists()) {  //文件必须存在
            System.out.println("要拷贝的源文件不存在!");
            return false;
        }
        if (!this.desFile.getParentFile().exists()) {
            this.desFile.getParentFile().mkdirs();  //如果父目录不存在就创建父目录
        }

        //byte data[] = new byte[1024];//开辟一个拷贝的缓冲区
        InputStream input = null;
        OutputStream output = null;

        try {
            input = new FileInputStream(this.srcFile);
            output = new FileOutputStream(this.desFile);
			/*
            int len = 0;//当len=-1的时候拷贝完成
            while ((len = input.read(data)) != -1) {
                output.write(data, 0, len);
            }
            */
            input.transferTo(output);//注释掉的部分即为被取代的部分
            return true;
        } catch (Exception e) {//异常类型太多,所以用Exception
            throw e;
        } finally {  //无论出不出错都要关闭
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }
}

public class fille {
    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();//用来计时耗时,开始时间

        FileUntil fu = new FileUntil("d:\\123.txt", "d:\\456\\789.txt");
        System.out.println(fu.copy() ? "拷贝成功" : "拷贝失败");//返回true就是拷贝成功,返回false就是拷贝失败

        long end = System.currentTimeMillis();//结束时间
        System.out.println("拷贝用时:" + (end - start));
    }
}

三、目录的拷贝

目录的拷贝需要利用到递归的方法,将文件层层拷贝过来
代码如下:

package filecopy;

import java.io.*;

class FileUntil {//定义一个文件操作工具类
    private File srcFile;//原路径
    private File desFile;//目标路径

    public FileUntil(String src, String des) {
        this(new File(src), new File(des));
    }

    public FileUntil(File srcFile, File desFile) {
        this.srcFile = srcFile;
        this.desFile = desFile;
    }

    public boolean copyDir() throws Exception { //目录拷贝处理
        this.copyImpl(this.srcFile);
        return true;
    }

    private void copyImpl(File file) throws Exception {//利用递归将目录中所有文件与目录拷贝处理
        if (file.isDirectory()) { //如果他是目录
            File results[] = file.listFiles(); //列出目录组成
            if (results != null) {
                for (int x = 0; x < results.length; x++) {
                    copyImpl(results[x]);  //目录的拷贝要用到递归
                }
            }
        } else { //如果是文件
            String newFilePath = file.getPath().replace(this.srcFile.getPath() + File.separator, "");
            //file.getPath()是获取文件的完整路径。由于在不同系统下,文件分隔符不同,所以用File.separator代替
            //此处replace的作用是:例如将ljx/abc/123,替换为abc/123,以便直接存入目标文件及中,防止出现 LLLjx/ljx/abc/123的现象
            File newFile = new File(this.desFile, newFilePath); //拷贝的目标路径
            this.copyFileImpl(file, newFile);
        }
    }

    private boolean copyFileImpl(File srcFile, File desFile) throws Exception { //一个公共的拷贝文件方法
        if (!desFile.getParentFile().exists()) {
            desFile.getParentFile().mkdirs();  //如果父目录不存在就创建父目录
        }

        InputStream input = null;
        OutputStream output = null;

        try {
            input = new FileInputStream(srcFile);
            output = new FileOutputStream(desFile);
            input.transferTo(output);  //JDK1.9之后才可以使用
            return true;
        } catch (Exception e) {//异常类型太多,所以用Exception
            throw e;
        } finally {  //无论出不出错都要关闭
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }

    public boolean copy() throws Exception {  //文件拷贝处理
        if (!this.srcFile.exists()) {  //文件必须存在
            System.out.println("要拷贝的源文件不存在!");
            return false;
        }
        return this.copyFileImpl(this.srcFile, this.desFile);
    }
}

public class file1 {
    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();//用来计时耗时,开始时间

        FileUntil fu = new FileUntil("d:\\ljx", "d:\\LLLjx");
        if (new File("d:\\ljx").isFile()) {  //是文件就调用拷贝文件方法
            System.out.println(fu.copy() ? "拷贝成功" : "拷贝失败");
        } else {  //是文目录就调用拷贝目录方法
            System.out.println(fu.copyDir() ? "拷贝成功" : "拷贝失败");
        }

        long end = System.currentTimeMillis();//结束时间
        System.out.println("拷贝用时:" + (end - start));
    }
}

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值