programing

Java를 사용하여 파일이 있는 폴더를 삭제하는 방법

randomtip 2022. 9. 30. 09:13
반응형

Java를 사용하여 파일이 있는 폴더를 삭제하는 방법

Java를 사용하여 디렉토리를 만들고 삭제하려고 하는데 작동하지 않습니다.

File index = new File("/home/Work/Indexer1");
if (!index.exists()) {
    index.mkdir();
} else {
    index.delete();
    if (!index.exists()) {
        index.mkdir();
    }
}

그냥 한 줄만.

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

매뉴얼은 이쪽

Java는 데이터가 있는 폴더를 삭제할 수 없습니다.폴더를 삭제하기 전에 모든 파일을 삭제해야 합니다.

다음과 같은 사용:

String[]entries = index.list();
for(String s: entries){
    File currentFile = new File(index.getPath(),s);
    currentFile.delete();
}

이 할 수 .index.delete()★★★★★★★★★★★★★★★★★★★!

이것은 기능합니다.디렉토리 테스트를 건너뛰는 것은 비효율적인 것처럼 보이지만 그렇지 않습니다.이치노listFiles().

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            deleteDir(f);
        }
    }
    file.delete();
}

업데이트: 심볼릭 링크가 표시되지 않도록 합니다.

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            if (! Files.isSymbolicLink(f.toPath())) {
                deleteDir(f);
            }
        }
    }
    file.delete();
}

Java 8에서 다음 솔루션을 사용하는 것이 좋습니다.

  Files.walk(pathToBeDeleted)
    .sorted(Comparator.reverseOrder())
    .map(Path::toFile)
    .forEach(File::delete);

사이트명: http://www.baeldung.com/java-delete-directory

에서는 JDK 7을 사용할 수 .Files.walkFileTree() ★★★★★★★★★★★★★★★★★」Files.deleteIfExists()파일 트리를 삭제합니다.(예: http://fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html)

JDK 6에서는 FileUtils.deleteQuietly를 Apache Commons에서 사용하면 파일, 디렉터리 또는 파일 및 하위 디렉터리가 있는 디렉터리를 제거할 수 있습니다.

Apache Commons-IO를 사용하여 다음과 같은 단일 항목을 수행합니다.

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

은 (입니다.FileUtils.deleteDirectory.

앞서 설명한 바와 같이 Java는 파일이 포함된 폴더를 삭제할 수 없으므로 먼저 파일을 삭제한 후 폴더를 삭제하십시오.

이를 위한 간단한 예를 다음에 제시하겠습니다.

import org.apache.commons.io.FileUtils;



// First, remove files from into the folder 
FileUtils.cleanDirectory(folder/path);

// Then, remove the folder
FileUtils.deleteDirectory(folder/path);

또는 다음 중 하나를 선택합니다.

FileUtils.forceDelete(new File(destination));

는 '봄의 '봄'의 '봄'의 '봄'의 '봄'을 하는 것입니다.org.springframework.util.FileSystemUtils디렉토리의 모든 내용을 재귀적으로 삭제하는 관련 메서드.

File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);

그걸로 충분해!

이전 버전의 JDK를 사용하는 기본 재귀 버전:

public static void deleteFile(File element) {
    if (element.isDirectory()) {
        for (File sub : element.listFiles()) {
            deleteFile(sub);
        }
    }
    element.delete();
}

입니다.Java 7+:

public static void deleteDirectory(String directoryFilePath) throws IOException
{
    Path directory = Paths.get(directoryFilePath);

    if (Files.exists(directory))
    {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException
            {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException
            {
                Files.delete(directory);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

구아바 21+를 구했다.삭제할 디렉터리를 가리키는 심볼 링크가 없는 경우에만 사용하십시오.

com.google.common.io.MoreFiles.deleteRecursively(
      file.toPath(),
      RecursiveDeleteOption.ALLOW_INSECURE
) ;

(이 질문은 Google에 의해 잘 색인화되어 있기 때문에, 다른 답안들과 중복되어 있더라도, 다른 사람들은 Guava를 기꺼이 찾을 수 있을 것이다.)

이거 드셔보세요

public static void deleteDir(File dirFile) {
    if (dirFile.isDirectory()) {
        File[] dirs = dirFile.listFiles();
        for (File dir: dirs) {
            deleteDir(dir);
        }
    }
    dirFile.delete();
}

저는 이 솔루션이 가장 마음에 듭니다.서드파티 라이브러리를 사용하지 않고 Java 7의 NIO2를 사용합니다.

/**
 * Deletes Folder with all of its content
 *
 * @param folder path to folder which should be deleted
 */
public static void deleteFolderAndItsContent(final Path folder) throws IOException {
    Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

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

2020년 이쪽 :)

Apache commons io FileUtils를 사용하면 "순수한" Java 변형과 달리 폴더를 비워둘 필요가 없습니다.더 나은 개요를 제공하기 위해 여기에 변종을 나열하겠습니다. 다음 세 가지 이유로 인해 예외가 발생할 수 있습니다.

  • clean Directory: 디렉토리를 삭제하지 않고 삭제합니다.
  • forceDelete:파일을 삭제합니다.파일이 디렉토리인 경우 해당 파일과 모든 하위 디렉토리를 삭제합니다.
  • forceDeleteOnExit:JVM이 종료될 때 파일이 삭제되도록 스케줄링합니다.파일이 디렉토리인 경우 해당 파일과 모든 하위 디렉토리를 삭제합니다.JVM이 곧 종료되지 않을 수 있으므로 서버 실행에는 권장되지 않습니다.

다음 변형에서는 예외가 발생하지 않습니다(파일이 null인 경우에도 마찬가지입니다.

  • deleteQuiety: 파일을 삭제하고 예외를 발생시키지 않습니다.디렉토리인 경우는, 그 디렉토리 및 모든 서브 디렉토리를 삭제합니다.

하나 더 알아야 할 것은 심볼 링크를 다루는 것입니다. 그러면 대상 폴더가 아닌 심볼 링크가 삭제됩니다.조심하세요.

또한 대용량 파일 또는 폴더를 삭제하는 것은 당분간 차단 작업이 될 수 있으므로 비동기식으로 실행해도 상관없습니다(실행자를 통한 백그라운드 스레드 등).

이 점에서.

index.delete();

            if (!index.exists())
               {
                   index.mkdir();
               }

당신이 전화하고 있다

 if (!index.exists())
                   {
                       index.mkdir();
                   }

끝나고

index.delete();

즉, 파일 삭제 후 파일을 다시 만듭니다.delete()는 부울 값을 반환합니다.확인하시려면 다음 절차를 따르세요.System.out.println(index.delete());true이 삭제되는 을 의미합니다.

File index = new File("/home/Work/Indexer1");
    if (!index.exists())
       {
             index.mkdir();
       }
    else{
            System.out.println(index.delete());//If you get true then file is deleted




            if (!index.exists())
               {
                   index.mkdir();// here you are creating again after deleting the file
               }




        }

아래 댓글에서 업데이트된 답변은 다음과 같습니다.

File f=new File("full_path");//full path like c:/home/ri
    if(f.exists())
    {
        f.delete();
    }
    else
    {
        try {
            //f.createNewFile();//this will create a file
            f.mkdir();//this create a folder
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

서브폴더가 있는 경우 Cemron 응답에 문제가 있습니다.따라서 다음과 같이 동작하는 방법을 작성해야 합니다.

private void deleteTempFile(File tempFile) {
        try
        {
            if(tempFile.isDirectory()){
               File[] entries = tempFile.listFiles();
               for(File currentFile: entries){
                   deleteTempFile(currentFile);
               }
               tempFile.delete();
            }else{
               tempFile.delete();
            }
        getLogger().info("DELETED Temporal File: " + tempFile.getPath());
        }
        catch(Throwable t)
        {
            getLogger().error("Could not DELETE file: " + tempFile.getPath(), t);
        }
    }

FileUtils.deleteDirectory를 사용할 수 있습니다.JAVA는 File.delete()사용하여 비어 있지 않은 폴더는 삭제할 수 없습니다.

directry는 파일이 있는 경우 단순히 삭제할 수 없기 때문에 먼저 내부 파일을 삭제한 후 디렉토리를 삭제해야 할 수 있습니다.

public class DeleteFileFolder {

public DeleteFileFolder(String path) {

    File file = new File(path);
    if(file.exists())
    {
        do{
            delete(file);
        }while(file.exists());
    }else
    {
        System.out.println("File or Folder not found : "+path);
    }

}
private void delete(File file)
{
    if(file.isDirectory())
    {
        String fileList[] = file.list();
        if(fileList.length == 0)
        {
            System.out.println("Deleting Directory : "+file.getPath());
            file.delete();
        }else
        {
            int size = fileList.length;
            for(int i = 0 ; i < size ; i++)
            {
                String fileName = fileList[i];
                System.out.println("File path : "+file.getPath()+" and name :"+fileName);
                String fullPath = file.getPath()+"/"+fileName;
                File fileOrFolder = new File(fullPath);
                System.out.println("Full Path :"+fileOrFolder.getPath());
                delete(fileOrFolder);
            }
        }
    }else
    {
        System.out.println("Deleting file : "+file.getPath());
        file.delete();
    }
}

, 그럼 이렇게 쓸 수 요.spring-core의존성

boolean result = FileSystemUtils.deleteRecursively(file);

JDK 클래스를 참조하는 대부분의 응답(최근에도 마찬가지)은 의존하지만 작업이 자동으로 실패할 수 있기 때문에 API에 결함이 있습니다.
java.io.File.delete()documentation states : " " " " :

에 주의:java.nio.file.Files합니다.deleteIOException★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★이는 오류 보고 및 파일을 삭제할 수 없는 이유를 진단하는 데 유용합니다.

대체 수단으로서, 당신은 이 방법을 선호해야 합니다.IOException에러 메세지가 표시됩니다.

실제 코드는 다음과 같이 기술할 수 있습니다.

Path index = Paths.get("/home/Work/Indexer1");

if (!Files.exists(index)) {
    index = Files.createDirectories(index);
} else {

    Files.walk(index)
         .sorted(Comparator.reverseOrder())  // as the file tree is traversed depth-first and that deleted dirs have to be empty  
         .forEach(t -> {
             try {
                 Files.delete(t);
             } catch (IOException e) {
                 // LOG the exception and potentially stop the processing

             }
         });
    if (!Files.exists(index)) {
        index = Files.createDirectories(index);
    }
}
private void deleteFileOrFolder(File file){
    try {
        for (File f : file.listFiles()) {
            f.delete();
            deleteFileOrFolder(f);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}
        import org.apache.commons.io.FileUtils;

        List<String> directory =  new ArrayList(); 
        directory.add("test-output"); 
        directory.add("Reports/executions"); 
        directory.add("Reports/index.html"); 
        directory.add("Reports/report.properties"); 
        for(int count = 0 ; count < directory.size() ; count ++)
        {
        String destination = directory.get(count);
        deleteDirectory(destination);
        }





      public void deleteDirectory(String path) {

        File file  = new File(path);
        if(file.isDirectory()){
             System.out.println("Deleting Directory :" + path);
            try {
                FileUtils.deleteDirectory(new File(path)); //deletes the whole folder
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else {
        System.out.println("Deleting File :" + path);
            //it is a simple file. Proceed for deletion
            file.delete();
        }

    }

Charm과 같이 동작합니다.폴더와 파일 모두에 대해서.Salam : )

서브 디렉토리가 존재하는 경우 재귀 호출을 할 수 있습니다.

import java.io.File;

class DeleteDir {
public static void main(String args[]) {
deleteDirectory(new File(args[0]));
}

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

또한 하위 폴더 및 파일이 포함된 폴더를 삭제할 수도 있습니다.

  1. 첫째, 재귀 함수를 만듭니다.

     private void recursiveDelete(File file){
    
             if(file.list().length > 0){
                 String[] list = file.list();
                 for(String is: list){
                     File currentFile = new File(file.getPath(),is);
                     if(currentFile.isDirectory()){
                             recursiveDelete(currentFile);
                     }else{
                         currentFile.delete();
                     }
                 }
             }else {
                 file.delete();
             }
         }
    
  2. 그런 다음 초기 함수에서 while loop을 사용하여 재귀 호출을 수행합니다.

     private boolean deleteFolderContainingSubFoldersAndFiles(){
    
             boolean deleted = false;
             File folderToDelete = new File("C:/mainFolderDirectoryHere");
    
             while(folderToDelete != null && folderToDelete.isDirectory()){
                 recursiveDelete(folderToDelete);
             }
    
             return deleted;
         }
    

간단한 방법은 다음과 같습니다.

public void deleteDirectory(String directoryPath)  {
      new Thread(new Runnable() {
          public void run() {
             for(String e: new File(directoryPath).list()) {
                 if(new File(e).isDirectory()) 
                     deleteDirectory(e);
                 else 
                     new File(e).delete();
             }
          }
      }).start();
  }
You can simply remove the directory which contains a single file or multiple files using the apache commons library.

gradle Import:

구현 그룹: 'disc-io', 이름: 'disc-io', 버전: '2.5'

File file=new File("/Users/devil/Documents/DummyProject/hello.txt");
    
 File parentDirLocation=new File(file.getParent);
    
//Confirming the file parent is a directory or not.
             
if(parentDirLocation.isDirectory){
    
    
 //after this line the mentioned directory will deleted.
 FileUtils.deleteDirectory(parentDirLocation);
   
 }
List<File> temp = Arrays.asList(new File("./DIRECTORY").listFiles());
for (int i = 0; i < temp.size(); i++)
{
    temp.get(i).delete();
}

다른 부품에서 제거

File index = new File("/home/Work/Indexer1");
if (!index.exists())
{
     index.mkdir();
     System.out.println("Dir Not present. Creating new one!");
}
index.delete();
System.out.println("File deleted successfully");

이러한 답변 중 일부는 불필요하게 길어 보입니다.

if (directory.exists()) {
    for (File file : directory.listFiles()) {
        file.delete();
    }
    directory.delete();
}

서브 디렉토리에도 사용할 수 있습니다.

이 기능을 사용할 수 있습니다.

public void delete()    
{   
    File f = new File("E://implementation1/");
    File[] files = f.listFiles();
    for (File file : files) {
        file.delete();
    }
}

언급URL : https://stackoverflow.com/questions/20281835/how-to-delete-a-folder-with-files-using-java

반응형