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
One more choice is to use Spring's org.springframework.util.FileSystemUtils
relevant method which will recursively delete all content of the directory.
File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);
That will do the job!
you can try as follows
File dir = new File("path");
if (dir.isDirectory())
{
dir.delete();
}
If there are sub folders inside your folder you may need to recursively delete them.
Most of answers (even recent) referencing JDK classes rely on File.delete() but that is a flawed API as the operation may fail silently.
The java.io.File.delete()
method documentation states :
Note that the
java.nio.file.Files
class defines thedelete
method to throw anIOException
when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
As replacement, you should favor Files.delete(Path p) that throws an IOException
with a error message.
The actual code could be written such as :
Path index = Paths.get("/home/Work/Indexer1");
if (!Files.exists(index)) {
index = Files.createDirectories(index);
} else {
Files.walk(index)
.sorted(Comparator.reverseOrder()) // as the file tree is traversed depth-first and that deleted dirs have to be empty
.forEach(t -> {
try {
Files.delete(t);
} catch (IOException e) {
// LOG the exception and potentially stop the processing
}
});
if (!Files.exists(index)) {
index = Files.createDirectories(index);
}
}
This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles()
.
void deleteDir(File file) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
deleteDir(f);
}
}
file.delete();
}
Update, to avoid following symbolic links:
void deleteDir(File file) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
if (! Files.isSymbolicLink(f.toPath())) {
deleteDir(f);
}
}
}
file.delete();
}
private void deleteFileOrFolder(File file){
try {
for (File f : file.listFiles()) {
f.delete();
deleteFileOrFolder(f);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
You can use this function
public void delete()
{
File f = new File("E://implementation1/");
File[] files = f.listFiles();
for (File file : files) {
file.delete();
}
}