Javaでディレクトリを再帰的に削除する
-
13-09-2019 - |
質問
Javaでディレクトリ全体を再帰的に削除する方法はありますか?
通常の場合、空のディレクトリを削除することができます。ただし、コンテンツを含むディレクトリ全体を削除する場合は、それほど単純ではありません。
Java でコンテンツを含むディレクトリ全体を削除するにはどうすればよいですか?
解決
あなたは Apacheのコモンズ-IO にチェックアウトする必要があります。それは<のhref = "// commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File)" のrelを持っていますあなたがやりたいだろう= "noreferrer">のfileutils のクラスます。
FileUtils.deleteDirectory(new File("directory"));
他のヒント
のJava 7で、我々は最終的に信頼性の高いシンボリックリンクを検出してこれを行うことができます。に(私はApacheのcommons-を考慮していませんそれはWindows上でリンクを処理しないようmklink
で作成され、この時点では、の信頼性のシンボリックリンクの検出を持っているioを。)
歴史のために、ここではの前のJava 7の答えは、シンボリックリンクをたどるのです。の
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
throw new FileNotFoundException("Failed to delete file: " + f);
}
Javaでは、あなたが Files
のクラスを使用することができます7+ 。コードは非常に簡単です。
Path directory = Paths.get("/tmp");
Files.walkFileTree(directory, 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 {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
のJava 7には、シンボリックリンクの扱いとディレクトリを歩くためのサポートを追加します:
import java.nio.file.*;
public static void removeRecursive(Path path) throws IOException
{
Files.walkFileTree(path, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
// try to delete the file anyway, even if its attributes
// could not be read, since delete-only access is
// theoretically possible
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
{
if (exc == null)
{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
else
{
// directory iteration failed; propagate exception
throw exc;
}
}
});
}
I(このの未試験のコードに)プラットフォーム固有の方法から代替としてこれを使用します
public static void removeDirectory(Path directory) throws IOException
{
// does nothing if non-existent
if (Files.exists(directory))
{
try
{
// prefer OS-dependent directory removal tool
if (SystemUtils.IS_OS_WINDOWS)
Processes.execute("%ComSpec%", "/C", "RD /S /Q \"" + directory + '"');
else if (SystemUtils.IS_OS_UNIX)
Processes.execute("/bin/rm", "-rf", directory.toString());
}
catch (ProcessExecutionException | InterruptedException e)
{
// fallback to internal implementation on error
}
if (Files.exists(directory))
removeRecursive(directory);
}
}
(SystemUtilsがhref="http://commons.apache.org/lang/">のApache Commonsのラングの
のワンライナー溶液(Java8)を再帰的にディレクトリを開始するなど、すべてのファイルとディレクトリを削除します:
Files.walk(Paths.get("c:/dir_to_delete/"))
.map(Path::toFile)
.sorted((o1, o2) -> -o1.compareTo(o2))
.forEach(File::delete);
私たちは、逆の順序のためのコンパレータを使用し、それ以外のファイル::削除する可能性が非空のディレクトリを削除することはできません。あなたがディレクトリを維持し、ファイルのみを削除したいのであれば、ただのコンパレータを削除)(ソートのまたはを完全に仕分け削除して、ファイルフィルタを追加します:
Files.walk(Paths.get("c:/dir_to_delete/"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(File::delete);
ちょうど私のソリューションは、エリクソンの、単なる静的メソッドとしてパッケージとほぼ同じである見ました。それは(あなたが見ることができるように)非常に簡単である何かのためのApache Commonsのすべてをインストールするよりもはるかに軽量です、このどこかをドロップします。
public class FileUtils {
/**
* By default File#delete fails for non-empty directories, it works like "rm".
* We need something a little more brutual - this does the equivalent of "rm -r"
* @param path Root File Path
* @return true iff the file and all sub files/directories have been removed
* @throws FileNotFoundException
*/
public static boolean deleteRecursive(File path) throws FileNotFoundException{
if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath());
boolean ret = true;
if (path.isDirectory()){
for (File f : path.listFiles()){
ret = ret && deleteRecursive(f);
}
}
return ret && path.delete();
}
}
スタックと再帰的メソッドを含まない溶液
File dir = new File("/path/to/dir");
File[] currList;
Stack<File> stack = new Stack<File>();
stack.push(dir);
while (! stack.isEmpty()) {
if (stack.lastElement().isDirectory()) {
currList = stack.lastElement().listFiles();
if (currList.length > 0) {
for (File curr: currList) {
stack.push(curr);
}
} else {
stack.pop().delete();
}
} else {
stack.pop().delete();
}
}
グアバ 持っていた Files.deleteRecursively(File)
までサポートされます グアバ 9.
から グアバ 10:
廃止されました。 この方法には、シンボリックリンクの検出が不十分で、競合状態が発生します。この機能は、次のようなオペレーティング システム コマンドをシェルアウトすることによってのみ適切にサポートできます。
rm -rf
またはdel /s
. このメソッドは、Guava リリース 11.0 の Guava から削除される予定です。
したがって、そのような方法はありません グアバ 11.
Springがある場合は、使用できます FileSystemUtils.deleteRecursively:
import org.springframework.util.FileSystemUtils;
boolean success = FileSystemUtils.deleteRecursively(new File("directory"));
for(Path p : Files.walk(directoryToDelete).
sorted((a, b) -> b.compareTo(a)). // reverse; files before dirs
toArray(Path[]::new))
{
Files.delete(p);
}
それとも、IOException
を処理する場合:
Files.walk(directoryToDelete).
sorted((a, b) -> b.compareTo(a)). // reverse; files before dirs
forEach(p -> {
try { Files.delete(p); }
catch(IOException e) { /* ... */ }
});
public void deleteRecursive(File path){
File[] c = path.listFiles();
System.out.println("Cleaning out folder:" + path.toString());
for (File file : c){
if (file.isDirectory()){
System.out.println("Deleting file:" + file.toString());
deleteRecursive(file);
file.delete();
} else {
file.delete();
}
}
path.delete();
}
static public void deleteDirectory(File path)
{
if (path == null)
return;
if (path.exists())
{
for(File f : path.listFiles())
{
if(f.isDirectory())
{
deleteDirectory(f);
f.delete();
}
else
{
f.delete();
}
}
path.delete();
}
}
シンボリックリンクと上記のコードで失敗する...と解決策を知らない2つの方法があります。
ウェイ#1
テストを作成するには、これを実行します:
echo test > testfile
mkdir dirtodelete
ln -s badlink dirtodelete/badlinktodelete
ここでは、あなたのテストファイルとテストディレクトリを参照してください。
$ ls testfile dirtodelete
testfile
dirtodelete:
linktodelete
次に、あなたのコモンズ-IO deleteDirectory()を実行します。これは、ファイルが見つからないと言ってクラッシュします。他の例がここで何をするかわかりません。 Linuxののrmコマンドは、単純に、ディレクトリ上のリンク、およびRM -rを考え削除します。
Exception in thread "main" java.io.FileNotFoundException: File does not exist: /tmp/dirtodelete/linktodelete
ウェイ#2
テストを作成するには、これを実行します:
mkdir testdir
echo test > testdir/testfile
mkdir dirtodelete
ln -s ../testdir dirtodelete/dirlinktodelete
ここでは、あなたのテストファイルとテストディレクトリを参照してください。
$ ls dirtodelete testdir
dirtodelete:
dirlinktodelete
testdir:
testfile
次に、あなたのコモンズ-IO deleteDirectory()または掲載サンプルコードの人々を実行します。それだけでなく、ディレクトリを削除しますが、ディレクトリの外にある、あなたのテストファイルは削除されています。 (これは、暗黙的にディレクトリを逆参照し、内容を削除します)。 RM -rは、リンクだけを削除します。あなたは間接参照ファイルを削除し、このようなものを使用する必要があります。「見つける-L dirtodelete型F -execのrm {} \;」
$ ls dirtodelete testdir
ls: cannot access dirtodelete: No such file or directory
testdir:
あなたが使用することができます:
org.apache.commons.io.FileUtils.deleteQuietly(destFile);
は、例外をスローすることはありません、ファイルを削除します。ファイルがディレクトリである場合、それは、すべてのサブディレクトリを削除します。 File.delete差()と、この方法は、次のとおり 削除するディレクトリは空である必要はありません。 ファイルまたはディレクトリが削除できない場合に例外がスローされません。の
メソッドからスローされた例外は、常にその方法がやろうとし(失敗した)されたかを説明すべきであるというアプローチで一貫して例外を処理し、最適なソリューション:
private void deleteRecursive(File f) throws Exception {
try {
if (f.isDirectory()) {
for (File c : f.listFiles()) {
deleteRecursive(c);
}
}
if (!f.delete()) {
throw new Exception("Delete command returned false for file: " + f);
}
}
catch (Exception e) {
throw new Exception("Failed to delete the folder: " + f, e);
}
}
レガシープロジェクトで、私はネイティブのJavaコードを作成する必要があります。私はPaulitexコードに似たこのコードを作成します。それを参照してください。
public class FileHelper {
public static boolean delete(File fileOrFolder) {
boolean result = true;
if(fileOrFolder.isDirectory()) {
for (File file : fileOrFolder.listFiles()) {
result = result && delete(file);
}
}
result = result && fileOrFolder.delete();
return result;
}
}
とユニットテスト:
public class FileHelperTest {
@Before
public void setup() throws IOException {
new File("FOLDER_TO_DELETE/SUBFOLDER").mkdirs();
new File("FOLDER_TO_DELETE/SUBFOLDER_TWO").mkdirs();
new File("FOLDER_TO_DELETE/SUBFOLDER_TWO/TEST_FILE.txt").createNewFile();
}
@Test
public void deleteFolderWithFiles() {
File folderToDelete = new File("FOLDER_TO_DELETE");
Assert.assertTrue(FileHelper.delete(folderToDelete));
Assert.assertFalse(new File("FOLDER_TO_DELETE").exists());
}
}
ここでは、コマンドライン引数を受け付け裸の骨の主な方法であり、あなた自身のエラーチェックを追加したり、合うどのようにそれを成形する必要がある場合があります。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DeleteFiles {
/**
* @param intitial arguments take in a source to read from and a
* destination to read to
*/
public static void main(String[] args)
throws FileNotFoundException,IOException {
File src = new File(args[0]);
if (!src.exists() ) {
System.out.println("FAILURE!");
}else{
// Gathers files in directory
File[] a = src.listFiles();
for (int i = 0; i < a.length; i++) {
//Sends files to recursive deletion method
fileDelete(a[i]);
}
// Deletes original source folder
src.delete();
System.out.println("Success!");
}
}
/**
* @param srcFile Source file to examine
* @throws FileNotFoundException if File not found
* @throws IOException if File not found
*/
private static void fileDelete(File srcFile)
throws FileNotFoundException, IOException {
// Checks if file is a directory
if (srcFile.isDirectory()) {
//Gathers files in directory
File[] b = srcFile.listFiles();
for (int i = 0; i < b.length; i++) {
//Recursively deletes all files and sub-directories
fileDelete(b[i]);
}
// Deletes original sub-directory file
srcFile.delete();
} else {
srcFile.delete();
}
}
}
私はそれが役に立てば幸い!
コードの下には、再帰的に指定したフォルダ内のすべての内容を削除します。
boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
たぶん、この問題の解決策は、エリクソンの答えからコードを使用して、Fileクラスのdeleteメソッドを再実装するかもしれません
public class MyFile extends File {
... <- copy constructor
public boolean delete() {
if (f.isDirectory()) {
for (File c : f.listFiles()) {
return new MyFile(c).delete();
}
} else {
return f.delete();
}
}
}
なしコモンズIOとpublic static void deleteRecursive(File path){
path.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
pathname.listFiles(this);
pathname.delete();
} else {
pathname.delete();
}
return false;
}
});
path.delete();
}
、ディレクトリが削除されるために、空であることが要求されています。簡単にこれを行うには再帰を使用します。たとえばます:
public static void clearFolders(String[] args) {
for(String st : args){
File folder = new File(st);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if(files!=null) {
for(File f: files) {
if (f.isDirectory()){
clearFolders(new String[]{f.getAbsolutePath()});
f.delete();
} else {
f.delete();
}
}
}
}
}
}
私は、より安全な使用のために3つの安全基準を持って、このルーチンをコード化されます。
package ch.ethz.idsc.queuey.util;
import java.io.File;
import java.io.IOException;
/** recursive file/directory deletion
*
* safety from erroneous use is enhanced by three criteria
* 1) checking the depth of the directory tree T to be deleted
* against a permitted upper bound "max_depth"
* 2) checking the number of files to be deleted #F
* against a permitted upper bound "max_count"
* 3) if deletion of a file or directory fails, the process aborts */
public final class FileDelete {
/** Example: The command
* FileDelete.of(new File("/user/name/myapp/recordings/log20171024"), 2, 1000);
* deletes given directory with sub directories of depth of at most 2,
* and max number of total files less than 1000. No files are deleted
* if directory tree exceeds 2, or total of files exceed 1000.
*
* abort criteria are described at top of class
*
* @param file
* @param max_depth
* @param max_count
* @return
* @throws Exception if criteria are not met */
public static FileDelete of(File file, int max_depth, int max_count) throws IOException {
return new FileDelete(file, max_depth, max_count);
}
// ---
private final File root;
private final int max_depth;
private int removed = 0;
/** @param root file or a directory. If root is a file, the file will be deleted.
* If root is a directory, the directory tree will be deleted.
* @param max_depth of directory visitor
* @param max_count of files to delete
* @throws IOException */
private FileDelete(final File root, final int max_depth, final int max_count) throws IOException {
this.root = root;
this.max_depth = max_depth;
// ---
final int count = visitRecursively(root, 0, false);
if (count <= max_count) // abort criteria 2)
visitRecursively(root, 0, true);
else
throw new IOException("more files to be deleted than allowed (" + max_count + "<=" + count + ") in " + root);
}
private int visitRecursively(final File file, final int depth, final boolean delete) throws IOException {
if (max_depth < depth) // enforce depth limit, abort criteria 1)
throw new IOException("directory tree exceeds permitted depth");
// ---
int count = 0;
if (file.isDirectory()) // if file is a directory, recur
for (File entry : file.listFiles())
count += visitRecursively(entry, depth + 1, delete);
++count; // count file as visited
if (delete) {
final boolean deleted = file.delete();
if (!deleted) // abort criteria 3)
throw new IOException("cannot delete " + file.getAbsolutePath());
++removed;
}
return count;
}
public int deletedCount() {
return removed;
}
public void printNotification() {
int count = deletedCount();
if (0 < count)
System.out.println("deleted " + count + " file(s) in " + root);
}
}
さて、例を想定してみましょう、
import java.io.File;
import java.io.IOException;
public class DeleteDirectory
{
private static final String folder = "D:/project/java";
public static void main(String[] args) throws IOException
{
File fl = new File(folder);
if(!fl.exists()) // checking if directory exists
{
System.out.println("Sorry!! directory doesn't exist.");
}
else
{
DeleteDirectory dd = new DeleteDirectory();
dd.deleteDirectory(fl);
}
}
public void deleteDirectory(File file) throws IOException
{
if(file.isDirectory())
{
if(file.list().length == 0)
{
deleteEmptyDirectory(file); // here if directory is empty delete we are deleting
}
else
{
File fe[] = file.listFiles();
for(File deleteFile : fe)
{
deleteDirectory(deleteFile); // recursive call
}
if(file.list().length == 0)
{
deleteEmptyDirectory(file);
}
}
}
else
{
file.delete();
System.out.println("File deleted : " + file.getAbsolutePath());
}
}
private void deleteEmptyDirectory(File fi)
{
fi.delete();
System.out.println("Directory deleted : " + fi.getAbsolutePath());
}
}
詳細については、リソース
の下に参照してください。ディレクトリを削除します。