source

Java에서 폴더 삭제

itover 2022. 12. 31. 16:38
반응형

Java에서 폴더 삭제

Java에서는 파일 및 폴더를 포함하는 폴더에 있는 모든 내용을 삭제하고 싶습니다.

public void startDeleting(String path) {
        List<String> filesList = new ArrayList<String>();
        List<String> folderList = new ArrayList<String>();
        fetchCompleteList(filesList, folderList, path);
        for(String filePath : filesList) {
            File tempFile = new File(filePath);
            tempFile.delete();
        }
        for(String filePath : folderList) {
            File tempFile = new File(filePath);
            tempFile.delete();
        }
    }

private void fetchCompleteList(List<String> filesList, 
    List<String> folderList, String path) {
    File file = new File(path);
    File[] listOfFile = file.listFiles();
    for(File tempFile : listOfFile) {
        if(tempFile.isDirectory()) {
            folderList.add(tempFile.getAbsolutePath());
            fetchCompleteList(filesList, 
                folderList, tempFile.getAbsolutePath());
        } else {
            filesList.add(tempFile.getAbsolutePath());
        }

    }

}

이 코드는 작동하지 않습니다. 가장 좋은 방법은 무엇입니까?

Apache Commons IO를 사용하면 다음과 같은 단일 라이너입니다.

FileUtils.deleteDirectory(dir);

FileUtils.deleteDirectory() 참조


Guava는 유사한 기능을 지원하는 데 사용됩니다.

Files.deleteRecursively(dir);

이것은 몇 년 전에 Guava에서 삭제되었습니다.


위 버전은 매우 간단하지만, 당신에게 말하지 않고 많은 추측을 하기 때문에 매우 위험합니다.따라서 대부분의 경우 안전할 수 있지만, 저는 "공식적인 방법"을 선호합니다(Java 7 이후).

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      Files.delete(file);
      return CONTINUE;
    }

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);
    }

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;
    }

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};

다음과 같은 것이 있습니다.

public static boolean deleteDirectory(File directory) {
    if(directory.exists()){
        File[] files = directory.listFiles();
        if(null!=files){
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
    }
    return(directory.delete());
}

이것을 시험해 보세요.

public static boolean deleteDir(File dir) 
{ 
  if (dir.isDirectory()) 
  { 
    String[] children = dir.list(); 
    for (int i=0; i<children.length; i++)
      return deleteDir(new File(dir, children[i])); 
  }  
  // The directory is now empty or this is a file so delete it 
  return dir.delete(); 
} 

중첩된 폴더에 문제가 있을 수 있습니다.코드가 발견된 순서대로 폴더를 삭제합니다.이것은 하향식으로 동작하지 않습니다.폴더 목록을 먼저 뒤집으면 작동할 수 있습니다.

다만 Commons IO와 같은 라이브러리를 사용하는 것이 좋습니다.

이 코드 조각이 더 안정적이고 효과가 있다는 걸 알았어요

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

    return dir.delete(); // The directory is empty now and can be deleted.
}

FileUtils.deleteDirectory() 메서드를 사용하면 디렉토리 및 그 아래에 있는 모든 것을 재귀적으로 삭제하는 프로세스를 단순화할 수 있습니다.

질문을 확인하세요.

제가 예전에 이런 방법을 썼어요.지정된 디렉토리를 삭제하고 디렉토리 삭제에 성공하면 true를 반환합니다.

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}

목록에 모든 (하위) 파일과 폴더를 반복적으로 저장하지만, 하위 파일을 저장하기 전에 현재 코드를 사용하여 상위 폴더를 저장합니다.따라서 폴더가 비어 있기 전에 삭제하려고 합니다.다음 코드를 사용해 보십시오.

   if(tempFile.isDirectory()) {
        // children first
        fetchCompleteList(filesList, folderList, tempFile.getAbsolutePath());
        // parent folder last
        folderList.add(tempFile.getAbsolutePath());
   }

File.delete()의 javadoc

퍼블릭 부울 삭제()

이 추상 경로 이름이 나타내는 파일 또는 디렉터리를 삭제합니다.이 pathname >이 디렉토리를 나타내는 경우 디렉토리를 삭제하려면 해당 디렉토리가 비어 있어야 합니다.

따라서 폴더는 비어 있어야 하며, 그렇지 않으면 삭제가 실패합니다.현재 코드는 폴더 목록을 맨 위의 폴더로 채우고 그 다음 하위 폴더로 채웁니다.하위 폴더를 삭제하기 전에 상위 폴더를 삭제하려는 것과 동일한 방법으로 목록을 반복하기 때문에 이 작업은 실패합니다.

이러한 회선의 변경

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

여기에

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

코드가 먼저 하위 폴더를 삭제하도록 합니다.

또한 삭제 조작은 실패 시 false를 반환하므로 필요에 따라 이 값을 체크하여 오류 처리를 수행할 수 있습니다.

폴더 내의 파일을 먼저 삭제하고 다음으로 폴더를 삭제해야 합니다.이렇게 하면 메서드가 재귀적으로 호출됩니다.

폴더를 재귀적으로 삭제합니다.

public static void folderdel(String path){
    File f= new File(path);
    if(f.exists()){
        String[] list= f.list();
        if(list.length==0){
            if(f.delete()){
                System.out.println("folder deleted");
                return;
            }
        }
        else {
            for(int i=0; i<list.length ;i++){
                File f1= new File(path+"\\"+list[i]);
                if(f1.isFile()&& f1.exists()){
                    f1.delete();
                }
                if(f1.isDirectory()){
                    folderdel(""+f1);
                }
            }
            folderdel(path);
        }
    }
}

언급URL : https://stackoverflow.com/questions/3775694/deleting-folder-from-java

반응형