java.io.File.renameTo文件系统问题
java.io.File中的renameTo方法尽量少用,因为可能会出现文件系统不一致问题导致文件移动失败。具体可能出现的问题包括:1、NTFS、FAT32 分区格式问题。2、文件分隔符问题\\和/。3、rename的文件存在。
public boolean renameTo(File dest) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
security.checkWrite(dest.path);
}
if (dest == null) {
throw new NullPointerException();
}
if (this.isInvalid() || dest.isInvalid()) {
return false;
}
return fs.rename(this, dest);
}
具体的实现在你当前对应的文件系统,最终调用了本地的rename0方法:
public boolean rename(File f1, File f2) {
// Keep canonicalization caches in sync after file deletion
// and renaming operations. Could be more clever than this
// (i.e., only remove/update affected entries) but probably
// not worth it since these entries expire after 30 seconds
// anyway.
cache.clear();
javaHomePrefixCache.clear();
return rename0(f1, f2);
}
private native boolean rename0(File f1, File f2);
推荐使用的方法:
if(!destFile.exists()){
FileUtils.copyFile(file, destFile);
file.delete();
}
参考:http://xiaoych.iteye.com/blog/149328