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)文章
Java中的MessageFormat.format用法實(shí)例
這篇文章主要介紹了Java中的MessageFormat.format用法實(shí)例,本文先是講解了MessageFormat的語(yǔ)法,然后給出了多個(gè)操作實(shí)例,需要的朋友可以參考下2015-06-06
springBoot的事件機(jī)制GenericApplicationListener用法解析
這篇文章主要介紹了springBoot的事件機(jī)制GenericApplicationListener用法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值的相關(guān)資料2019-09-09
解決Mybatis?plus實(shí)體類屬性與表字段不一致的問題
這篇文章主要介紹了Mybatis?plus實(shí)體類屬性與表字段不一致解決方法,文末給大家提到了Mybatis-plus中數(shù)據(jù)庫(kù)表名和表字段名的相關(guān)知識(shí),需要的朋友可以參考下2022-07-07
Liquibase結(jié)合SpringBoot使用實(shí)現(xiàn)數(shù)據(jù)庫(kù)管理功能
Liquibase 是一個(gè)強(qiáng)大的數(shù)據(jù)庫(kù)管理工具,它幫助你通過自動(dòng)化管理數(shù)據(jù)庫(kù)的變更、版本控制、和回滾,簡(jiǎn)化了開發(fā)中的數(shù)據(jù)庫(kù)遷移工作,這篇文章主要介紹了Liquibase結(jié)合SpringBoot使用實(shí)現(xiàn)數(shù)據(jù)庫(kù)管理,需要的朋友可以參考下2024-12-12
SpringBoot集成JmsTemplate(隊(duì)列模式和主題模式)及xml和JavaConfig配置詳解
這篇文章主要介紹了SpringBoot集成JmsTemplate(隊(duì)列模式和主題模式)及xml和JavaConfig配置詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08

