简单的Java练习--文件文件夹复制

1.文件及文件夹路径
在G盘中有一个新建文件夹,其中有一个a文件夹和一张图片,在a文件夹中有b文件夹和一个吧"b.txt"文件,在b文件夹中有一个"c.txt"文件,两个文件均有内容。
2.代码

package com.igeek;

import java.io.*;

/**
 * @Author:
 * @ClassName:
 * @Description:copy
 * @Date: Create in 16:17 2021/4/18
 */
public class CopyFile {
    public static void main(String[] args) throws IOException {
        File src = new File("G:\\新建文件夹");//源文件
        File dest = new File("F:\\");//目标文件
        copyMethod(src,dest);//复制方法
    }
    public static void copyMethod(File src,File dest) throws IOException {
        File[] frr1 = src.listFiles();//创建File数组
        for (File f : frr1){
            if (f.isDirectory()){
                String s1 = f.getName();
                String s2 = dest.getAbsolutePath();//获取目标文件绝对路径
                String s3 = s2+"\\"+s1;
                File f1 = new File(s3);
                f1.mkdir();
                copyMethod(f,f1);//递归
            }else {
                String s4 = f.getName();
                String s5 = dest.getAbsolutePath();
                String s6 = s5+"\\"+s4;
                File f2 = new File(s6);
                copyFile(f,f2);//文件复制方法
            }
        }
    }
     public static void copyFile(File src , File dest) throws IOException {
     	//使用的时字节流
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest));
         int len = -1;
         while ((len = bis.read())!= -1){
             bos.write(len);
         }
         bos.close();
         bis.close();
     }
}

3.此代码比较简陋,并没有判断文件夹是否为空,目标文件夹下是否有相同的文件或文件夹,下次更正

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值