最近在coding Java复制文件夹的时候,比较懒,直接百度了一个方法,直接使用到项目中,后面再调用重命名方法的时候,总是返回false,“视野”不开阔,百度了很久不思其解。“改装”后的copyFolder也有回收文件流呀,为什么不行呢。 后面仔细一看, 在复制文件的时候,存在子文件是文件夹的情况,然后会迭代调用函数自己,这时候可能流的回收不够彻底,一怒之下,直接全部包了try cache 在finally的时候,全部回收。 仿佛all in了一样,这次再不行,真的要跪了..... 但是,真的成功了。下面贴下代码,“改装” 之后可能还有问题,望指出...
/**
* 复制整个文件夹内容
* @param oldPath String 原文件路径 如:c:/fqf
* @param newPath String 复制后路径 如:f:/fqf/ff
* @return boolean
* @throws IOException
*/
public static void copyFolder(String oldPath, String newPath) throws Exception {
FileInputStream input = null;
FileOutputStream output = null;
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File oldFile = new File(oldPath);
String[] oldFileChildFile = oldFile.list();
File temp = null;
for (int i = 0; i < oldFileChildFile.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath + oldFileChildFile[i]);
}else{
temp=new File(oldPath + File.separator+oldFileChildFile[i]);
}
if(temp.isFile()){
try {
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);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null != input){
input.close();
}
if(null != output){
output.flush();
output.close();
}
}
}
if(temp.isDirectory()){//如果是子文件夹
try {
copyFolder(oldPath+"/"+oldFileChildFile[i],newPath+"/"+oldFileChildFile[i]);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(null != input){
input.close();
}
if(null != output){
output.flush();
output.close();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("复制整个文件夹内容操作出错");
} finally{
if(null != input){
input.close();
}
if(null != output){
output.flush();
output.close();
}
}
}
据说,重命名方法renameTo在linux下会有问题,用common-io的重命名就不会有事了吗?求解答...