温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-29 20:31:27 来源:脚本之家 阅读:167 作者:qq_22672291 栏目:编程语言

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI