我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。
这可能吗?如果可能,怎么可能?
我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。
这可能吗?如果可能,怎么可能?
当前回答
这是kotlin选项。它运行得很好。
fun executeDelete(context: Context, paths: List<String>): Int {
return try {
val files = paths.map { File(it) }
val fileCommands = files.joinToString(separator = " ") {
if (it.isDirectory) "'${it.absolutePath}/'" else "'${it.absolutePath}'"
}
val command = "rm -rf $fileCommands"
val process = Runtime.getRuntime().exec(arrayOf("sh", "-c", command))
val result = process.waitFor()
if (result == 0) {
context.rescanPaths(paths)
}
result
} catch (e: Exception) {
-1
}
}
//避免在一行中多次调用,它可以删除整个文件夹内容
fun Context.rescanPaths(paths: List<String>, callback: (() -> Unit)? = null) {
if (paths.isEmpty()) {
callback?.invoke()
return
}
var cnt = paths.size
MediaScannerConnection.scanFile(applicationContext, paths.toTypedArray(), null) { _, _ ->
if (--cnt == 0) {
callback?.invoke()
}
}
}
其他回答
这是kotlin选项。它运行得很好。
fun executeDelete(context: Context, paths: List<String>): Int {
return try {
val files = paths.map { File(it) }
val fileCommands = files.joinToString(separator = " ") {
if (it.isDirectory) "'${it.absolutePath}/'" else "'${it.absolutePath}'"
}
val command = "rm -rf $fileCommands"
val process = Runtime.getRuntime().exec(arrayOf("sh", "-c", command))
val result = process.waitFor()
if (result == 0) {
context.rescanPaths(paths)
}
result
} catch (e: Exception) {
-1
}
}
//避免在一行中多次调用,它可以删除整个文件夹内容
fun Context.rescanPaths(paths: List<String>, callback: (() -> Unit)? = null) {
if (paths.isEmpty()) {
callback?.invoke()
return
}
var cnt = paths.size
MediaScannerConnection.scanFile(applicationContext, paths.toTypedArray(), null) { _, _ ->
if (--cnt == 0) {
callback?.invoke()
}
}
}
这就是我的工作…(简洁且经过测试)
...
deleteDir(new File(dir_to_be_deleted));
...
// delete directory and contents
void deleteDir(File file) {
if (file.isDirectory())
for (String child : file.list())
deleteDir(new File(file, child));
file.delete(); // delete child file or empty directory
}
让我告诉你第一件事你不能删除DCIM文件夹,因为它是一个系统文件夹。当你在手机上手动删除它时,它会删除该文件夹的内容,但不会删除DCIM文件夹。您可以通过以下方法删除其内容:
根据评论更新
File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
如果你不需要递归删除东西,你可以尝试这样做:
File file = new File(context.getExternalFilesDir(null), "");
if (file != null && file.isDirectory()) {
File[] files = file.listFiles();
if(files != null) {
for(File f : files) {
f.delete();
}
}
}
根据文档:
如果此抽象路径名不表示目录,则此方法返回null。
所以你应该检查listFiles是否为空,如果不是则继续
boolean deleteDirectory(File path) {
if(path.exists()) {
File[] files = path.listFiles();
if (files == null) {
return false;
}
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
boolean wasSuccessful = file.delete();
if (wasSuccessful) {
Log.i("Deleted ", "successfully");
}
}
}
}
return(path.delete());
}