文件夹的拷贝
这里用到了递归运算,即在方法里调用本方法。
拷贝文件就是我们平时用到的文件拷贝,拷贝文件夹就是递归进入文件夹内,在判断当前是文件夹还是文件,接着进行下一步。。。。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DirCopy {
/**
* @author 会会会会
* @param args
* @exception 文件夹的拷贝
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
copyDir("IOTest01", "IOdest");
}
//拷贝文件夹
public static void copyDir(String src, String dest) {
File filesrc = new File(src);
File filedest = new File(dest);
File[] listFiles = filesrc.listFiles();
if (!filedest.exists()) {
filedest.mkdir();
}
for (File file : listFiles) {
if (file.isFile()) {
copyFile(file.getPath(), dest + "\\" + file.getName());
} else if (file.isDirectory()) {
filedest.mkdir();
copyDir(file.getPath(), dest + "\\" + file.getName());
}
}
}
// 拷贝文件
public static void copyFile(String src, String dest) {
File fsrc = new File(src);// 源头
File fdest = new File(dest);// 目的地
OutputStream os = null;
InputStream is = null;
try {
is = new FileInputStream(fsrc);// 将源头输入到内存
os = new FileOutputStream(fdest);// 准备将内存资源输出
byte[] flush = new byte[1024];// 设置缓冲流
int len = -1;// 定义字节节点
while ((len = is.read(flush)) != -1) {// 判断结束
os.write(flush, 0, len);// 字节写入输入
}
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}