前言
最近做项目遇到一个需求:
1.要求当app版本升级覆盖安装后,清除app部分功能的本地缓存。
正好需要用到「重命名文件」和「删除文件」操作。
1. 重命名文件
renameTo 方法
/**
* 重命名文件:
* oldPath 和 newPath必须是新旧文件的绝对路径
*/
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 方法
/**
* 对文件夹下的文件进行清扫
*
* @param topDir 文件夹目录
* @param skips 需要保存不被清扫的文件
* @param rmTopDir 是否清扫父文件 true:清扫 false:不清扫
* @return 清扫结果
*/
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)) {
//判断是否包含不被清扫的文件,如果包含,则不delete
if (!skips.contains(file.getAbsolutePath())) {
return file.delete();
} else {
return true;
}
}
//遍历
for (File f : childFiles) {
final String absPath = f.getAbsolutePath();
//判断是否包含不被清扫的文件,如果包含,则不delete
if (!skips.contains(absPath)) {
if (!cleanupDirFiles(absPath, skips, true)) {
return false;
}
}
}
}
//判断是否清扫父文件
if (rmTopDir && (!skips.contains(file.getAbsolutePath()))) {
return file.delete();
}
}
return true;
}