Java使用遞歸復制文件夾及文件夾
更新時間:2020年05月14日 14:34:48 作者:Draogn
這篇文章主要介紹了Java使用遞歸復制文件夾及文件夾,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
遞歸調(diào)用copyDir方法實現(xiàn),查詢源文件目錄使用字節(jié)輸入流寫入字節(jié)數(shù)組,如果目標文件目錄沒有就創(chuàng)建目錄,如果迭代出是文件夾使用字節(jié)輸出流對拷文件,直至源文件目錄沒有內(nèi)容。
/**
* 復制文件夾
* @param srcDir 源文件目錄
* @param destDir 目標文件目錄
*/
public static void copyDir(String srcDir, String destDir) {
if (srcRoot == null) srcRoot = srcDir;
//源文件夾
File srcFile = new File(srcDir);
//目標文件夾
File destFile = new File(destDir);
//判斷srcFile有效性
if (srcFile == null || !srcFile.exists())
return;
//創(chuàng)建目標文件夾
if (!destFile.exists())
destFile.mkdirs();
//判斷是否是文件
if (srcFile.isFile()) {
//源文件的絕對路徑
String absPath = srcFile.getAbsolutePath();
//取出上級目錄
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);
}
}
}
}
/**
* 復制文件夾
*
* @param path 路徑
* @param destDir 目錄
*/
public static void copyFile(String path, String destDir) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
/*
準備目錄
取出相對的路徑
創(chuàng)建目標文件所在的文件目錄
*/
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ù)組進行流對拷
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();
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java中的MessageFormat.format用法實例
這篇文章主要介紹了Java中的MessageFormat.format用法實例,本文先是講解了MessageFormat的語法,然后給出了多個操作實例,需要的朋友可以參考下2015-06-06
springBoot的事件機制GenericApplicationListener用法解析
這篇文章主要介紹了springBoot的事件機制GenericApplicationListener用法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值的相關資料2019-09-09
Liquibase結合SpringBoot使用實現(xiàn)數(shù)據(jù)庫管理功能
Liquibase 是一個強大的數(shù)據(jù)庫管理工具,它幫助你通過自動化管理數(shù)據(jù)庫的變更、版本控制、和回滾,簡化了開發(fā)中的數(shù)據(jù)庫遷移工作,這篇文章主要介紹了Liquibase結合SpringBoot使用實現(xiàn)數(shù)據(jù)庫管理,需要的朋友可以參考下2024-12-12
SpringBoot集成JmsTemplate(隊列模式和主題模式)及xml和JavaConfig配置詳解
這篇文章主要介紹了SpringBoot集成JmsTemplate(隊列模式和主題模式)及xml和JavaConfig配置詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08

