获取文件或文件夹大小
fun File.size(): Long {
var size = 0L
try {
if (isFile) {
size += length()
}
if (isDirectory) {
listFiles().forEach {
size += it.size()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return size
}
删除文件或文件夹
fun File.suicide() {
if (isFile) delete()
if (isDirectory) listFiles().forEach { it.suicide() }
}
获取缓存大小
- (也就是cache文件夹和files文件夹的大小,sf等其他的暂未考虑,我也不清楚还有什么需要考虑的)
private fun getCacheSize(context: Context): Long {
val cacheSize = (context as SettingsAct).cacheDir.size()
val fileSize = context.filesDir.size()
return cacheSize + fileSize
}
清除一般操作
fun clearCache(context: Context) {
val cacheSize = getCacheSize(context)
if (cacheSize > 0) {
context.alert("清除所有缓存?", "清除", "取消") {
(context as SettingsAct).cacheDir.suicide()
context.filesDir.suicide()
message.value = "成功清除${cacheSize.formatMemorySize()}缓存"
this.cacheSize.set("0K")
}
} else message.value = "无需清理"
}
//show alert dialog
fun Context.alert(message: String, confirmText: String, cancelText: String, onConfirm: () -> Unit) {
AlertDialog.Builder(this)
.setMessage(message)
.setNegativeButton(cancelText) { dialog, _ -> dialog.dismiss() }
.setPositiveButton(confirmText) { dialog, _ ->
dialog.dismiss()
onConfirm()
}.show()
}
- formatMemorySize是Long的扩展方法
fun Long.formatMemorySize(): String {
val kiloByte = this / 1024.toDouble()
val megaByte = kiloByte / 1024
if (megaByte < 1) {
return kiloByte.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "K"
}
val gigaByte = megaByte / 1024
if (gigaByte < 1) {
return megaByte.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "M"
}
val teraBytes = megaByte / 1024
if (teraBytes < 1) {
return megaByte.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "G"
}
return teraBytes.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "T"
}
网友评论