Kotlin 31. Kotlin 如何删除文件或文件夹

Kotlin 如何删除文件或文件夹

比如,我们想要删除 Documents/年月日 文件夹下面的所有文件(包括这个文件夹),我们首先需要获得 Documents 的路径:

val extDir: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)

然后,我们选择 年月日,并和上面的路径合并:

val currentTime = Date(Calendar.getInstance().time.time)
val formatter = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
val currentTimeFormat = formatter.format(currentTime)
val directory2Del = File(extDir,currentTimeFormat)

最后,我们将这个文件夹以及里面所有的文件进行删除:

try {
    
    
    directory2Del.deleteRecursively()
    Log.i("ImageFolderDel", "Directory deleted successfully.")
} catch (e: Exception) {
    
    
    Log.i("ImageFolderDel", "Fail to delete image folder.")
    e.printStackTrace()
}

又比如,我们需要删除 Documents/年月日/年月日.png文件,我们可以这么写:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    try {
        val fileName = "$currentTimeFormat.png"
        val file2Del = File(directory2Del,fileName)
        val path = Paths.get(file2Del.path)
        val result = Files.deleteIfExists(path)
        if (result) {
            Log.i("FileDel", "File deleted successfully.")
        } else {
            Log.i("FileDel", "File deleted failed.")
        }
    } catch (e: IOException) {
        Log.i("FileDel", "File deleted failed.")
        e.printStackTrace()
    }
}

猜你喜欢

转载自blog.csdn.net/zyctimes/article/details/129051515