您好,登錄后才能下訂單哦!
整理文檔,搜刮出一個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í)有所幫助,也希望大家多多支持億速云。
免責(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)容。