Javaでディレクトリを削除する方法

Javaでディレクトリを削除する方法

ディレクトリを削除するには、File.delete()を使用するだけですが、削除するにはディレクトリが空である必要があります。

多くの場合、recursive delete in a directoryを実行する必要があります。これは、すべてのサブディレクトリとファイルも削除する必要があることを意味します。以下の例を参照してください。

ディレクトリの再帰削除の例

C:\example-new」という名前のディレクトリと、そのすべてのサブディレクトリとファイルも削除します。 コードは自明であり、十分に文書化されており、簡単に理解できるはずです。

package com.example.file;

import java.io.File;
import java.io.IOException;

public class DeleteDirectoryExample
{
    private static final String SRC_FOLDER = "C:\\example-new";

    public static void main(String[] args)
    {

        File directory = new File(SRC_FOLDER);

        //make sure directory exists
        if(!directory.exists()){

           System.out.println("Directory does not exist.");
           System.exit(0);

        }else{

           try{

               delete(directory);

           }catch(IOException e){
               e.printStackTrace();
               System.exit(0);
           }
        }

        System.out.println("Done");
    }

    public static void delete(File file)
        throws IOException{

        if(file.isDirectory()){

            //directory is empty, then delete it
            if(file.list().length==0){

               file.delete();
               System.out.println("Directory is deleted : "
                                                 + file.getAbsolutePath());

            }else{

               //list all the directory contents
               String files[] = file.list();

               for (String temp : files) {
                  //construct the file structure
                  File fileDelete = new File(file, temp);

                  //recursive delete
                 delete(fileDelete);
               }

               //check the directory again, if empty then delete it
               if(file.list().length==0){
                 file.delete();
                 System.out.println("Directory is deleted : "
                                                  + file.getAbsolutePath());
               }
            }

        }else{
            //if file, then delete it
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }
}

結果

File is deleted : C:\example-new\404.php
File is deleted : C:\example-new\archive.php
...
Directory is deleted : C:\example-new\includes
File is deleted : C:\example-new\index.php
File is deleted : C:\example-new\index.php.hacked
File is deleted : C:\example-new\js\hoverIntent.js
File is deleted : C:\example-new\js\jquery-1.4.2.min.js
File is deleted : C:\example-new\js\jquery.bgiframe.min.js
Directory is deleted : C:\example-new\js\superfish-1.4.8\css
Directory is deleted : C:\example-new\js\superfish-1.4.8\images
Directory is deleted : C:\example-new\js\superfish-1.4.8
File is deleted : C:\example-new\js\superfish-navbar.css
...
Directory is deleted : C:\example-new
Done