您的位置:首页 > 编程语言 > Java开发

Java实现Copy

2007-06-21 08:54 309 查看
假定源文件夹为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();
}
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: