public static void main(String[] args) {
// 指定文件夹路径
// copy("D:/code/eclipse-workspace/crawl_dmtp", "D:/copy");
copy("src", "D:/copy");
System.out.println("共移动文件数目:" + size);
}
/**
* 拷贝文件夹里面所有内容
*
* @param sourcePath
* @param newPath
*/
public static void copy(String sourcePath, String newPath) {
File file = new File(sourcePath);
if (file != null && file.exists()) {
String name = newPath + "/" + sourcePath.substring(sourcePath.lastIndexOf("/") + 1, sourcePath.length());
// 创建文件夹
File dir = new File(name);
if (!dir.exists()) {
dir.mkdir();
}
// 调用拷贝文件的主方法
copyDir(sourcePath, name);
} else {
return;
}
}
private static int size;
/**
* 拷贝文件夹
*
* @param sourcePath原文件夹
* @param newPath指定文件夹
*/
private static void copyDir(String sourcePath, String newPath) {
File sourceFile = new File(sourcePath);
if (sourceFile.exists() && sourceFile != null) {// 文件存在
if (sourceFile.isFile()) {
copyFile(sourcePath, newPath);
System.out.println(sourcePath + " ---> " + newPath);
size++;
} else if (sourceFile.isDirectory()) {
// 创建文件夹
File dir = new File(newPath);
if (!dir.exists()) {
dir.mkdir();
}
// 获取文件夹内部的文件
// 递归调用
for (File con : sourceFile.listFiles()) {
copyDir(sourcePath + "/" + con.getName(), newPath + "/" + con.getName());
// System.out.println(sourcePath + "/" + con.getName() + "-----" + newPath + "/" + con.getName());
}
}
} else {
return;
}
}
/**
* 拷贝文件
*
* @param oldFilePath资源文件
* @param newPath指定文件
*/
private static void copyFile(String soucePath, String newPath) {
// 1、确定源
File sourceFile = new File(soucePath);
File newFile = new File(newPath);
// 2、确定流
InputStream fin = null;
OutputStream fout = null;
try {
fin = new FileInputStream(sourceFile);
fout = new FileOutputStream(newFile);
// 3、确定操作
byte[] flush = new byte[1024];
int len = -1;
while ((len = fin.read(flush)) != -1) {
fout.write(flush, 0, len);
}
// 清空缓冲区
fout.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 4、关闭流,先打开的后关闭
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}