Java实现文件或文件夹的复制到指定目录实例

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
  
public class Test { 
  private static int a = 5; 
  
  public static void main(String[] args) { 
    //需要复制的目标文件或目标文件夹 
    String pathname = "C:/Users/likun/Desktop/git_project"; 
    File file = new File(pathname); 
    //复制到的位置 
    String topathname = "C:/Users/likun/Desktop/movie"; 
    File toFile = new File(topathname); 
    try { 
      copy(file, toFile); 
    } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
  } 
  
  public static void copy(File file, File toFile) throws Exception { 
    byte[] b = new byte[1024]; 
    int a; 
    FileInputStream fis; 
    FileOutputStream fos; 
    if (file.isDirectory()) { 
      String filepath = file.getAbsolutePath(); 
      filepath=filepath.replaceAll("\\\\", "/"); 
      String toFilepath = toFile.getAbsolutePath(); 
      toFilepath=toFilepath.replaceAll("\\\\", "/"); 
      int lastIndexOf = filepath.lastIndexOf("/"); 
      toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length()); 
      File copy=new File(toFilepath); 
      //复制文件夹 
      if (!copy.exists()) { 
        copy.mkdir(); 
      } 
      //遍历文件夹 
      for (File f : file.listFiles()) { 
        copy(f, copy); 
      } 
    } else { 
      if (toFile.isDirectory()) { 
        String filepath = file.getAbsolutePath(); 
        filepath=filepath.replaceAll("\\\\", "/"); 
        String toFilepath = toFile.getAbsolutePath(); 
        toFilepath=toFilepath.replaceAll("\\\\", "/"); 
        int lastIndexOf = filepath.lastIndexOf("/"); 
        toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length()); 
          
        //写文件 
        File newFile = new File(toFilepath); 
        fis = new FileInputStream(file); 
        fos = new FileOutputStream(newFile); 
        while ((a = fis.read(b)) != -1) { 
          fos.write(b, 0, a); 
        } 
      } else { 
        //写文件 
        fis = new FileInputStream(file); 
        fos = new FileOutputStream(toFile); 
        while ((a = fis.read(b)) != -1) { 
          fos.write(b, 0, a); 
        } 
      } 
  
    } 
  } 
  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值