之前需要批量转移文件的时候整理过,不记得是在哪里百度到的,自己整理用了还行以此记录,如果涉及到侵权请联系我删除!
public static void copyFolder(String oldPath, String newPath) {
try {
File a = new File(oldPath);
if(!a.exists()){
return;
}
String[] file = a.list();
if(file.length<=0){
return;
}
File mFile = new File(newPath);
if(!mFile .exists()){
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
}
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()) {
String fileName = newPath + "/" + (temp.getName()).toString();
File testFile = new File(fileName);
if (!testFile.exists()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(fileName);
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()) {// 如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}