前言
最近做项目遇到一个需求: 1.要求当app版本升级覆盖安装后,清除app部分功能的本地缓存。 正好需要用到「重命名文件」和「删除文件」操作。
1. 重命名文件
renameTo 方法
public static boolean renameFile(String oldPath, String newPath) {
if (TextUtils.isEmpty(oldPath)) {
return false;
}
if (TextUtils.isEmpty(newPath)) {
return false;
}
File oldFile = new File(oldPath);
File newFile = new File(newPath);
if (newFile.exists()) {
return false;
}
return oldFile.renameTo(newFile);
}
2. 删除文件
delete 方法
public static boolean cleanupDirFiles(@NonNull final String topDir, @NonNull final Set<String> skips, boolean rmTopDir) {
final File file = new File(topDir);
if (!file.exists()) {
return false;
} else {
if (file.isDirectory()) {
final File[] childFiles = file.listFiles();
if ((null == childFiles) || (childFiles.length <= 0)) {
if (!skips.contains(file.getAbsolutePath())) {
return file.delete();
} else {
return true;
}
}
for (File f : childFiles) {
final String absPath = f.getAbsolutePath();
if (!skips.contains(absPath)) {
if (!cleanupDirFiles(absPath, skips, true)) {
return false;
}
}
}
}
if (rmTopDir && (!skips.contains(file.getAbsolutePath()))) {
return file.delete();
}
}
return true;
}
|