programing

전체 폴더 및 내용을 삭제하는 방법은 무엇입니까?

instargram 2023. 7. 31. 21:04
반응형

전체 폴더 및 내용을 삭제하는 방법은 무엇입니까?

프로그램 사용자가 DCIM 폴더(SD 카드에 있고 하위 폴더가 포함되어 있음)를 삭제할 수 있도록 합니다.

만약 그렇다면 이것이 어떻게 가능합니까?

다음과 같이 파일 및 폴더를 재귀적으로 삭제할 수 있습니다.

void deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
        for (File child : fileOrDirectory.listFiles())
            deleteRecursive(child);

    fileOrDirectory.delete();
}

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();
    }
}

명령줄 인수를 사용하여 전체 폴더와 폴더 내용을 삭제할 수 있습니다.

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/");

코틀린에서 사용할 수 있습니다.deleteRecursively()로부터의 연장.kotlin.io꾸러미

val someDir = File("/path/to/dir")
someDir.deleteRecursively()

짧은 콜틴 버전

fun File.deleteDirectory(): Boolean {
    return if (exists()) {
        listFiles()?.forEach {
            if (it.isDirectory) {
                it.deleteDirectory()
            } else {
                it.delete()
            }
        }
        delete()
    } else false
}

갱신하다

코틀린 stdlib 함수

file.deleteRecursively()

파일과 하위 디렉터리를 포함하는 전체 기본 디렉터리를 삭제하려면 아래 방법을 사용합니다.이 메서드를 다시 한 번 호출한 후 기본 디렉토리의 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를 기반으로 합니다 ;)

디렉토리 정리 클래스를 만들었습니다. 디렉토리 정리가 필요할 때마다 도움이 됩니다.

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'  

설명서에 따르면:

이 추상 경로 이름이 디렉터리를 나타내지 않으면 이 메서드는 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());
}

반복적으로 삭제할 필요가 없는 경우 다음과 같은 작업을 수행할 수 있습니다.

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();
            }
        }
    }
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

가장 빠르고 쉬운 방법:

public static boolean deleteFolder(File removableFolder) {
        File[] files = removableFolder.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                boolean success;
                if (file.isDirectory())
                    success = deleteFolder(file);
                else success = file.delete();
                if (!success) return false;
            }
        }
        return removableFolder.delete();
}

이게 내가 하는 일...(간단하고 테스트됨)

    ...
    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
    }
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");
    }
}

디렉토리에서 모든 파일을 삭제하는 간단한 방법:

호출만으로 디렉토리에서 모든 이미지를 삭제하는 일반적인 기능입니다.

모든 이미지 파일(컨텍스트)을 삭제합니다.

public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
        if (directory.isDirectory()) {
            for (String fileName: file.list()) {
                new File(file,fileName).delete();
            }
        }    
    } 

내가 아는 가장 안전한 코드:

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();
}

파일이 있는지 확인하고, null을 처리하며, 디렉터리가 실제로 삭제되었는지 확인합니다.

//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) {
    }
}

여기 당신의 해결책이 있습니다. 그것은 또한 갤러리를 새롭게 할 것입니다.

제공된 디렉토리를 포함한 모든 하위 파일하위 디렉토리를 삭제합니다.

  1. 한다면File
  2. 한다면Empty Directory
  3. 한다면Not Empty Directory하위 디렉터리를 사용하여 삭제를 다시 호출합니다. 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;
}

다음은 재미를 위한 비재귀적 구현입니다.

/**
 * 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);
        }
    }
}

디렉토리 구조를 가진 폴더를 삭제하는 속도가 빠르긴 하지만 이것을 넣었습니다.

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;

}

이게 도움이 되길 바랍니다.

그러나 그것을 해결하기 위한 또 다른 (현대적인) 방법.

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();
        }
    }
}

이 재귀 함수를 사용하여 작업을 수행합니다.

public static void deleteDirAndContents(@NonNull File mFile){
    if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
        for (File file : mFile.listFiles()) {
            deleteDirAndContents(file);
        }
    } else {
        mFile.delete();
    }
}

이 함수는 디렉터리인지 파일인지 확인합니다.

디렉터리에 하위 파일이 있는지 확인하는 경우 하위 파일이 있으면 하위 파일을 전달하고 반복하는 자신을 다시 호출합니다.

파일인 경우 삭제합니다.

(캐시 디렉터리를 전달하여 앱 캐시를 지우는 데 이 기능을 사용하지 마십시오. 캐시 디렉터리도 삭제되어 앱이 충돌합니다.)캐시를 지우려면 전달된 dir를 삭제하지 않는 이 기능을 사용합니다.

public static void deleteDirContents(@NonNull File mFile){
        if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
            for (File file : mFile.listFiles()) {
                deleteDirAndContents(file);
            }
        }
    }

또는 다음을 사용하여 캐시 디렉토리인지 확인할 수 있습니다.

if (!mFile.getAbsolutePath().equals(context.getCacheDir().getAbsolutePath())) {
    mFile.delete();
}

앱 캐시를 지우는 코드 예:

public static void clearAppCache(Context context){
        try {
            File cache = context.getCacheDir();
            FilesUtils.deleteDirContents(cache);
        } catch (Exception e){
            MyLogger.onException(TAG, e);
        }
    }

안녕, 좋은 하루 되세요 & 코딩 :D

코틀린 옵션입니다.아주 잘 작동했습니다.

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()
    }
}
}

언급URL : https://stackoverflow.com/questions/4943629/how-to-delete-a-whole-folder-and-content

반응형