假定源文件夾爲D:/網絡管理,目標文件夾爲D:/網絡管理2,將目錄及子目錄下的文件做拷貝
package test;
import java.io.*;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class Copys {
public static void main(String args[]) {
File file = new File("D://網絡管理");
File tofile = new File("D://網絡管理2");
tofile.mkdirs();//建立目標文件夾
//指定源文件夾和目標文件夾參數,調用toCopyf方法
toCopyf(file, tofile);
}
/**
* 持貝指定的目錄下所有文件及子目錄到目標文件夾
* */
public static void toCopyf(File file, File tofile) {
//獲取源目錄下一級所有目錄文件
File[] files = file.listFiles();
//逐個判斷,創建目錄,執行遞歸調用
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
File copyPath = new File(tofile.getAbsolutePath() + "//" +
files[i].getName());
copyPath.mkdir();
toCopyf(files[i],copyPath);
} else { //如果file爲文件,讀取字節流寫入目標文件;
try {
FileInputStream fiStream = new FileInputStream(files[i]);
BufferedInputStream biStream = new BufferedInputStream(
fiStream);
File copyFile = new File(tofile.getAbsolutePath()
+ "//" + files[i].getName());
copyFile.createNewFile();
FileOutputStream foStream = new FileOutputStream(copyFile);
BufferedOutputStream boStream = new BufferedOutputStream(
foStream);
int j;
while ((j = biStream.read()) != -1) {
boStream.write(j);
}
/*關閉流*/
biStream.close();
boStream.close();
fiStream.close();
foStream.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}