溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java實(shí)現(xiàn)文件或文件夾的復(fù)制到指定目錄實(shí)例

發(fā)布時間:2020-08-29 20:31:27 來源:腳本之家 閱讀:180 作者:qq_22672291 欄目:編程語言

整理文檔,搜刮出一個Java實(shí)現(xiàn)文件或文件夾的復(fù)制到指定目錄的代碼,稍微整理精簡一下做下分享。

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) { 
    //需要復(fù)制的目標(biāo)文件或目標(biāo)文件夾 
    String pathname = "C:/Users/likun/Desktop/git_project"; 
    File file = new File(pathname); 
    //復(fù)制到的位置 
    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); 
      //復(fù)制文件夾 
      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); 
        } 
      } 
 
    } 
  } 
 
} 

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI