JAVA 复制文件夹(含子目录)

来源:互联网 发布:数据库用户是什么 编辑:程序博客网 时间:2024/05/22 05:01
/**
* 复制文件夹(含子目录)

* @param oldPath
*            e:/temp
* @param newPath
*            f:/
*/
public static void copyFolderWithSelf(String oldPath, String newPath) {
FileInputStream input = null;
FileOutputStream output = null;
try {
new File(newPath).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File dir = new File(oldPath);
// 目标
newPath += dir.getName() + File.separator;
File moveDir = new File(newPath);
if (dir.isDirectory()) {
if (!moveDir.exists()) {
moveDir.mkdirs();
}
}
if (dir != null) {
String[] file = dir.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
input = new FileInputStream(temp);
output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) { // 如果是子文件夹
copyFolderWithSelf(oldPath + "/" + file[i], newPath);
}
}
}


} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
0 0
原创粉丝点击