ディレクトリを削除するには、
File.delete()
を使うだけですが、削除するにはディレクトリを空にする必要があります。
しばしば、ディレクトリ
内で
再帰的な削除を実行する必要があるかもしれません。つまり、それはすべてのサブディレクトリであり、ファイルも同様に削除する必要があります。以下の例を参照してください。
ディレクトリ再帰的削除の例
”
C:\\ mkyong-new
“という名前のディレクトリを削除します。すべてのサブディレクトリとファイルも削除されます。コードは自明であり、十分に文書化されているので、理解しやすいはずです。
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class DeleteDirectoryExample
{
private static final String SRC__FOLDER = "C:\\mkyong-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:\mkyong-new\404.php File is deleted : C:\mkyong-new\archive.php ... ディレクトリが削除されました:C:\ mkyong-new \ includes ファイルが削除されました:C:\ mkyong-new \ index.php ファイルが削除されました:C:\ mkyong-new \ index.php.hacked ファイルが削除されました:C:\ mkyong-new \ js \ hoverIntent.js ファイルは削除されます:C:\ mkyong-new \ js \ jquery-1.4.2.min.js ファイルは削除されます:C:\ mkyong-new \ js \ jquery.bgiframe.min.js ディレクトリが削除されました:C:\ mkyong-new \ js \ superfish-1.4.8 \ css ディレクトリが削除されました:C:\ mkyong-new \ js \ superfish-1.4.8 \ images ディレクトリが削除されました:C:\ mkyong-new \ js \ superfish-1.4.8 ファイルは削除されます:C:\ mkyong-new \ js \ superfish-navbar.css ... ディレクトリが削除されました:C:\ mkyong-new 完了
ディレクトリの削除
リンク://タグ/ディレクトリ/[ディレクトリ]リンク://タグ/io/[io]リンク://タグ/java/[java]