Java實現(xiàn)文件或文件夾的復(fù)制到指定目錄實例
更新時間:2017年03月29日 17:09:06 作者:qq_22672291
本篇文章主要介紹了Java實現(xiàn)文件或文件夾的復(fù)制到指定目錄實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
整理文檔,搜刮出一個Java實現(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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用JavaConfig代替xml實現(xiàn)Spring配置操作
這篇文章主要介紹了使用JavaConfig代替xml實現(xiàn)Spring配置操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
Spring解決循環(huán)依賴問題的三種方法小結(jié)
在 Spring 中,循環(huán)依賴問題指的是兩個或多個 bean 之間相互依賴形成的閉環(huán),具體而言,當(dāng) bean A 依賴于 bean B,同時 bean B 也依賴于 bean A,就形成了循環(huán)依賴,本文就給大家介紹了Spring解決循環(huán)依賴問題的三種方法,需要的朋友可以參考下2023-09-09
關(guān)于request.getRequestDispatcher().forward()的妙用及DispatcherType
這篇文章主要介紹了關(guān)于request.getRequestDispatcher().forward()的妙用及DispatcherType對Filter配置的影響,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
SpringBoot啟動報錯Whitelabel Error Page: This&nbs
當(dāng)我們使用Spring Boot框架開發(fā)Web應(yīng)用時,有時會遇到啟動報錯信息為"Whitelabel Error Page: This application has no explicit mapping for",種報錯信息意味著我們的應(yīng)用缺少某個URL映射的配置,導(dǎo)致請求無法處理,在本篇文章中,我們將詳細(xì)討論如何解決這個問題2024-03-03

