Deleting files using recursive processing [Java]

Introduction

This article will show you how to delete files and directories using recursive processing. This is my first post, so if you have any comments, please comment!

Implementation

/**
 *Delete files recursively
 * @param file File or directory to delete
 */
public static void deleteFile(File file) {
		
	//Exit if the file does not exist
	if (!file.exists()) {
		return;
	}	
	//Delete child if it is a directory
	if (file.isDirectory()) {
		for (File child : file.listFiles()) {
			deleteFile(child);
		}
	}		
	//Delete the target file
	file.delete();
}

If it is a directory, it can be deleted in an empty state by deleting the child file object first.

bonus

For a while, I was happy to be able to use recursive processing, but after all there were many pioneers ... lol It's a waste to end with this, so I'll introduce a little more advanced one!

/**
 *Count only the number of files contained in a file or directory
 * @param file file or directory
 * @number of return files
 */
public static int countFile(File file) {				
	int count = 0;	
	//Exit if the file does not exist
	if (!file.exists()) {
		return count;
	}
	//Recursively count children if it is a directory,If it is a file, it counts itself
	if (file.isDirectory()) {
		for (File child : file.listFiles()) {
			count += countFile(child);
		}
	} else {
		count = 1;
	}
	//Return the total
	return count;
}

The above method can only count the number of files that exist under the argument object! Aside from the practicality of this method, I like recursive processing because it feels like programming.

Recommended Posts

Deleting files using recursive processing [Java]
Data processing using stream API from Java 8
Java thread processing
Java string processing
[Java] Stream processing
java iterative processing
Sorting using java comparator
Scraping practice using Java ②
Scraping practice using Java ①
JAVA constructor call processing
Java random, various processing
[Java] Development with multiple files using package and import
How to play MIDI files using the Java Sound API
Try using RocksDB in Java
Read binary files in Java 1
[Java] Timer processing implementation method
Read binary files in Java 2
Using Mapper with Java (Spring)
Measured parallel processing in Java
I tried using Java REPL
Understanding Java Concurrent Processing (Introduction)
Using Docker from Java Gradle
[Swift] Asynchronous processing using PromiseKit
[Processing] Try using GT Force.
Csv output processing using super-csv
Deleting Exif information using sanselan
Make a rhombus using Java
Summary of java error processing
Bubble sort using ArrayList (JAVA)