注意:File.renameTo方法有一定的局限性
Many aspects of the behavior of this method are inherently * platform-dependent: The rename operation might not be able to move a * file from one filesystem to another, it might not be atomic, and it * might not succeed if a file with the destination abstract pathname * already exists. The return value should always be checked to make sure * that the rename operation was successful.
重命名操作不能从一个文件系统移动到另一个文件系统,文件已经存在,则操作失败,返回false。所以要通过监控返回值,检查操作是否成功。
public boolean moveFiles(String oldPath, String newPath){
boolean result = true;
String[] filePaths = new File(oldPath).list();
if (filePaths != null && filePaths.length > 0){
if (!new File(newPath).exists()){
if(!new File(newPath).mkdirs()){
System.out.println("文件夹创建失败");
return false;
}
}
try{
for (String filePath : filePaths) {
if (new File(oldPath + File.separator + filePath).isDirectory()){
moveFiles(oldPath + File.separator + filePath, newPath + File.separator + filePath);
}else if (new File(oldPath + File.separator + filePath).isFile()){
//复制文件到另一个目录
copyFile(oldPath + File.separator + filePath, newPath + File.separator + filePath);
//移动文件至另一个目录
if(!new File(oldPath + File.separator + filePath).renameTo(new File(newPath + File.separator + filePath))){
System.out.println(oldPath + File.separator + filePath +"文件复制失败");
result = false;
break;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
return result;
}
public void copyFile(String oldPath, String newPath) throws IOException {
File oldFile = new File(oldPath);
File file = new File(newPath);
FileInputStream in = new FileInputStream(oldFile);
FileOutputStream out = new FileOutputStream(file);;
byte[] buffer=new byte[2097152];
while((in.read(buffer)) != -1){
out.write(buffer);
}
}