我希望我的应用程序的用户能够删除DCIM文件夹(位于SD卡上并包含子文件夹)。
如果可能的话,这可能吗?
rm -rf directory
代替FileUtils.deleteDirectory
。基准测试后,我们发现它快了好几倍。在此处查看示例实现:stackoverflow.com/a/58421350/293280
我希望我的应用程序的用户能够删除DCIM文件夹(位于SD卡上并包含子文件夹)。
如果可能的话,这可能吗?
rm -rf directory
代替FileUtils.deleteDirectory
。基准测试后,我们发现它快了好几倍。在此处查看示例实现:stackoverflow.com/a/58421350/293280
Answers:
让我告诉您第一件事,您不能删除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();
}
}
您可以像这样递归删除文件和文件夹:
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
DCIM\foo\bar\pic.jpg
),在这种情况下,chirag的代码将失败。
fileOrDirectory.listFiles()
可能null
存在NPE:如果在读取文件时出现I / O错误,则可能会返回NPE 。这在文档中有明确说明:developer.android.com/reference/java/io/File.html#listFiles()
我们可以使用命令行参数来删除整个文件夹及其内容。
public static void deleteFiles(String path) {
File file = new File(path);
if (file.exists()) {
String deleteCmd = "rm -r " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) { }
}
}
上面代码的示例用法:
deleteFiles("/sdcard/uploads/");
在Kotlin中,您可以使用deleteRecursively()
扩展kotlin.io
包
val someDir = File("/path/to/dir")
someDir.deleteRecursively()
FilesKt.deleteRecursively(new File("/path/to/dir"));
如果您使用的是kotlin-stdlib,则可以使用
使用以下方法删除包含文件及其子目录的整个主目录。再次调用此方法后,请调用主目录的delete()目录。
// For to Delete the directory inside list of files and inner Directory
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
对于仅包含文件的文件夹,您的方法很不错,但是如果您要查找还包含子文件夹的方案,则需要递归
另外,您应该捕获退货的退货价值,以确保允许您删除文件
并包括
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在你的清单上
void DeleteRecursive(File dir)
{
Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
if (temp.isDirectory())
{
Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
DeleteRecursive(temp);
}
else
{
Log.d("DeleteRecursive", "Delete File" + temp.getPath());
boolean b = temp.delete();
if (b == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}
}
}
dir.delete();
}
有很多答案,但是我决定添加自己的答案,因为两者几乎没有什么不同。它基于OOP;)
我创建了DirectoryCleaner类,每次需要清理某个目录时都会提供帮助。
public class DirectoryCleaner {
private final File mFile;
public DirectoryCleaner(File file) {
mFile = file;
}
public void clean() {
if (null == mFile || !mFile.exists() || !mFile.isDirectory()) return;
for (File file : mFile.listFiles()) {
delete(file);
}
}
private void delete(File file) {
if (file.isDirectory()) {
for (File child : file.listFiles()) {
delete(child);
}
}
file.delete();
}
}
它可以用于解决以下问题:
File dir = new File(Environment.getExternalStorageDirectory(), "your_directory_name");
new DirectoryCleaner(dir).clean();
dir.delete();
如果目录具有Java中的子目录或文件,则无法删除该目录。试试这个两行简单的解决方案。这将删除目录并在目录内进行比赛。
File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);
在gradle文件中添加此行并同步项目
compile 'org.apache.commons:commons-io:1.3.2'
public static void deleteDirectory( File dir )
{
if ( dir.isDirectory() )
{
String [] children = dir.list();
for ( int i = 0 ; i < children.length ; i ++ )
{
File child = new File( dir , children[i] );
if(child.isDirectory()){
deleteDirectory( child );
child.delete();
}else{
child.delete();
}
}
dir.delete();
}
}
参见android.os.FileUtils,它隐藏在API 21上
public static boolean deleteContents(File dir) {
File[] files = dir.listFiles();
boolean success = true;
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
success &= deleteContents(file);
}
if (!file.delete()) {
Log.w("Failed to delete " + file);
success = false;
}
}
}
return success;
}
来源:https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/FileUtils.java#414
根据文档:
如果此抽象路径名不表示目录,则此方法返回null。
因此,您应该检查是否listFiles
存在null
,如果没有则继续
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());
}
private static void deleteRecursive(File dir)
{
//Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
deleteRecursive(temp);
}
}
if (dir.delete() == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}
我知道的最安全的代码:
private boolean recursiveRemove(File file) {
if(file == null || !file.exists()) {
return false;
}
if(file.isDirectory()) {
File[] list = file.listFiles();
if(list != null) {
for(File item : list) {
recursiveRemove(item);
}
}
}
if(file.exists()) {
file.delete();
}
return !file.exists();
}
检查文件是否存在,处理空值,检查目录是否实际删除
这是一个非递归的实现,只是为了好玩:
/**
* Deletes the given folder and all its files / subfolders.
* Is not implemented in a recursive way. The "Recursively" in the name stems from the filesystem command
* @param root The folder to delete recursively
*/
public static void deleteRecursively(final File root) {
LinkedList<File> deletionQueue = new LinkedList<>();
deletionQueue.add(root);
while(!deletionQueue.isEmpty()) {
final File toDelete = deletionQueue.removeFirst();
final File[] children = toDelete.listFiles();
if(children == null || children.length == 0) {
// This is either a file or an empty directory -> deletion possible
toDelete.delete();
} else {
// Add the children before the folder because they have to be deleted first
deletionQueue.addAll(Arrays.asList(children));
// Add the folder again because we can't delete it yet.
deletionQueue.addLast(toDelete);
}
}
}
这(尝试删除所有子文件和子目录,包括提供的目录):
File
删除Empty Directory
删除Not Empty Directory
,使用子目录再次调用delete,则重复1到3例:
File externalDir = Environment.getExternalStorageDirectory()
Utils.deleteAll(externalDir); //BE CAREFUL.. Will try and delete ALL external storage files and directories
要访问外部存储目录,您需要以下权限:
(使用ContextCompat.checkSelfPermission
和ActivityCompat.requestPermissions
)
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
递归方法:
public static boolean deleteAll(File file) {
if (file == null || !file.exists()) return false;
boolean success = true;
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
if (f.isDirectory()) {
success &= deleteAll(f);
}
if (!f.delete()) {
Log.w("deleteAll", "Failed to delete " + f);
success = false;
}
}
} else {
if (!file.delete()) {
Log.w("deleteAll", "Failed to delete " + file);
success = false;
}
}
} else {
if (!file.delete()) {
Log.w("deleteAll", "Failed to delete " + file);
success = false;
}
}
return success;
}
我已经尽力将它删除具有任何目录结构的文件夹。
public int removeDirectory(final File folder) {
if(folder.isDirectory() == true) {
File[] folderContents = folder.listFiles();
int deletedFiles = 0;
if(folderContents.length == 0) {
if(folder.delete()) {
deletedFiles++;
return deletedFiles;
}
}
else if(folderContents.length > 0) {
do {
File lastFolder = folder;
File[] lastFolderContents = lastFolder.listFiles();
//This while loop finds the deepest path that does not contain any other folders
do {
for(File file : lastFolderContents) {
if(file.isDirectory()) {
lastFolder = file;
lastFolderContents = file.listFiles();
break;
}
else {
if(file.delete()) {
deletedFiles++;
}
else {
break;
}
}//End if(file.isDirectory())
}//End for(File file : folderContents)
} while(lastFolder.delete() == false);
deletedFiles++;
if(folder.exists() == false) {return deletedFiles;}
} while(folder.exists());
}
}
else {
return -1;
}
return 0;
}
希望这可以帮助。
//To delete all the files of a specific folder & subfolder
public static void deleteFiles(File directory, Context c) {
try {
for (File file : directory.listFiles()) {
if (file.isFile()) {
final ContentResolver contentResolver = c.getContentResolver();
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
if (file.exists()) {
file.delete();
if (file.exists()) {
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if (file.exists()) {
c.deleteFile(file.getName());
}
}
}
} else
deleteFiles(file, c);
}
} catch (Exception e) {
}
}
这是您的解决方案,它也会刷新图库。
解决它的另一种(现代)方法。
public class FileUtils {
public static void delete(File fileOrDirectory) {
if(fileOrDirectory != null && fileOrDirectory.exists()) {
if(fileOrDirectory.isDirectory() && fileOrDirectory.listFiles() != null) {
Arrays.stream(fileOrDirectory.listFiles())
.forEach(FileUtils::delete);
}
fileOrDirectory.delete();
}
}
}
从API 26开始在Android上
public class FileUtils {
public static void delete(File fileOrDirectory) {
if(fileOrDirectory != null) {
delete(fileOrDirectory.toPath());
}
}
public static void delete(Path path) {
try {
if(Files.exists(path)) {
Files.walk(path)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
// .peek(System.out::println)
.forEach(File::delete);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}