Java使用遞歸復(fù)制文件夾及文件夾
遞歸調(diào)用copyDir方法實(shí)現(xiàn),查詢?cè)次募夸浭褂米止?jié)輸入流寫入字節(jié)數(shù)組,如果目標(biāo)文件目錄沒有就創(chuàng)建目錄,如果迭代出是文件夾使用字節(jié)輸出流對(duì)拷文件,直至源文件目錄沒有內(nèi)容。
/**
* 復(fù)制文件夾
* @param srcDir 源文件目錄
* @param destDir 目標(biāo)文件目錄
*/
public static void copyDir(String srcDir, String destDir) {
if (srcRoot == null) srcRoot = srcDir;
//源文件夾
File srcFile = new File(srcDir);
//目標(biāo)文件夾
File destFile = new File(destDir);
//判斷srcFile有效性
if (srcFile == null || !srcFile.exists())
return;
//創(chuàng)建目標(biāo)文件夾
if (!destFile.exists())
destFile.mkdirs();
//判斷是否是文件
if (srcFile.isFile()) {
//源文件的絕對(duì)路徑
String absPath = srcFile.getAbsolutePath();
//取出上級(jí)目錄
String parentDir = new File(srcRoot).getParent();
//拷貝文件
copyFile(srcFile.getAbsolutePath(), destDir);
} else { //如果是目錄
File[] children = srcFile.listFiles();
if (children != null) {
for (File f : children) {
copyDir(f.getAbsolutePath(), destDir);
}
}
}
}
/**
* 復(fù)制文件夾
*
* @param path 路徑
* @param destDir 目錄
*/
public static void copyFile(String path, String destDir) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
/*
準(zhǔn)備目錄
取出相對(duì)的路徑
創(chuàng)建目標(biāo)文件所在的文件目錄
*/
String tmp = path.substring(srcRoot.length());
String folder = new File(destDir, tmp).getParentFile().getAbsolutePath();
File destFolder = new File(folder);
destFolder.mkdirs();
System.out.println(folder); //創(chuàng)建文件輸入流
fis = new FileInputStream(path);
//定義新路徑
//創(chuàng)建文件 輸出流
fos = new FileOutputStream(new File(destFolder,new File(path).getName()));
//創(chuàng)建字節(jié)數(shù)組進(jìn)行流對(duì)拷
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何修改json字符串中某個(gè)key對(duì)應(yīng)的value值
這篇文章主要介紹了如何修改json字符串中某個(gè)key對(duì)應(yīng)的value值操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-11-11
如何使用BeanUtils.copyProperties進(jìn)行對(duì)象之間的屬性賦值
這篇文章主要介紹了使用BeanUtils.copyProperties進(jìn)行對(duì)象之間的屬性賦值,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Java中保留兩位小數(shù)的四種方法實(shí)現(xiàn)實(shí)例
今天小編就為大家分享一篇關(guān)于Java中保留兩位小數(shù)的四種方法實(shí)現(xiàn)實(shí)例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02
Spring中的@CrossOrigin注解的使用詳細(xì)解讀
這篇文章主要介紹了Spring中的@CrossOrigin注解的使用詳細(xì)解讀,跨源資源共享(CORS),是由大多數(shù)瀏覽器實(shí)現(xiàn)的W3C規(guī)范,允許對(duì)跨域請(qǐng)求進(jìn)行靈活授權(quán),用來代替IFRAME或JSONP等非正規(guī)實(shí)現(xiàn)方式,需要的朋友可以參考下2023-11-11
SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解
這篇文章主要為大家介紹了SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

