Java实现文件或文件夹的复制到指定目录实例-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

创新互联:于2013年成立为各行业开拓出企业自己的“网站建设”服务,为近千家公司企业提供了专业的成都做网站、成都网站制作、网页设计和网站推广服务, 按需制作网站由设计师亲自精心设计,设计的效果完全按照客户的要求,并适当的提出合理的建议,拥有的视觉效果,策划师分析客户的同行竞争对手,根据客户的实际情况给出合理的网站构架,制作客户同行业具有领先地位的。

整理文档,搜刮出一个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); 
        } 
      } 
 
    } 
  } 
 
} 

网站栏目:Java实现文件或文件夹的复制到指定目录实例-创新互联
分享地址:http://myzitong.com/article/djjsid.html