How to delete a folder with files using Java

后端 未结 28 3030
北荒
北荒 2020-11-28 05:36

I want to create and delete a directory using Java, but it isn\'t working.

File index = new File(\"/home/Work/Indexer1\");
if (!index.exists()) {
    index.m         


        
相关标签:
28条回答
  • 2020-11-28 06:02

    If you have subfolders, you will find troubles with the Cemron answers. so you should create a method that works like this:

    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);
            }
        }
    
    0 讨论(0)
  • 2020-11-28 06:02

    Remove it from else part

    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");
    
    0 讨论(0)
  • 2020-11-28 06:03
            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();
            }
    
        }
    

    Works like a Charm . For both folder and files . Salam :)

    0 讨论(0)
  • 2020-11-28 06:04

    This is the best solution for 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;
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-11-28 06:04

    2020 here :)

    With Apache commons io FileUtils, contrary to the "pure" Java variants a folder does not need to be empty to be deleted. To give you a better overview I list the variants here, the following 3 may throw exceptions for various reasons:

    • cleanDirectory: Cleans a directory without deleting it
    • forceDelete: Deletes a file. If file is a directory, delete it and all sub-directories
    • forceDeleteOnExit: Schedules a file to be deleted when JVM exits. If file is directory delete it and all sub-directories. Not recommended for running servers as JVM may not exit any time soon ...

    The following variant never throws exceptions (even if the file is null !)

    • deleteQuietly: Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.

    One more thing to know is dealing with symbolic links, it will delete the symbolic link and not the target folder... be careful.

    Also keep in mind that deleting a large file or folder can be a blocking operation for a good while ... so if you do not mind having it run async do it (in a background thread via executor for example).

    0 讨论(0)
  • 2020-11-28 06:06

    we can use the spring-core dependency;

    boolean result = FileSystemUtils.deleteRecursively(file);
    
    0 讨论(0)
提交回复
热议问题