java实现文件的复制。

package com.shikun.tool;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Toolclass {
    // f1为对象文件路径,f2为目标文件路径
    public static void copyfloder(File f1, File f2) throws IOException {
        if (f1.isDirectory()) {
            File newfile = new File(f2, f1.getName());
            // 如果路径不存在创建一个路径
            newfile.mkdirs();

            File[] filearr = f1.listFiles();
            for (File ff : filearr) {
                copyfloder(ff, newfile);
            }
        } else {
            File newFile = new File(f2, f1.getName());
            copyfiles(f1, newFile);
        }
    }
    private static void copyfiles(File file1, File file2) throws IOException {
        // 创建输入输出流缓冲区
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
        byte[] bys = new byte[1024];
        int len = 0;
        // 读取源目标路径文件内容
        while ((len = bis.read(bys)) > 0) {
            bos.write(bys, 0, len);
        }
        bis.close();
        bos.close();
    }

}

--------------------------------测试类-------------------------------------------------------------------------

package com.shikun.tool;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class TestTool {

    public static void main(String[] args) throws IOException  {
        // TODO Auto-generated method stub
          //封装文件对象
        String path1="";
        String path2="";
        Scanner sc=new Scanner(System.in);
        System.out.print("源文件路径:");
        path1=sc.nextLine();
        System.out.print("目标文件路径:");
        path2=sc.nextLine();
        File f1=new File(path1);
        File f2=new File(path2);
        Toolclass.copyfloder(f1, f2);
        System.out.println("复制完成");
        sc.close();   
     }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值