Java delete all file in folder

How to delete a directory recursively in Java

In an earlier article, we looked at different ways of deleting a directory in Java. In this article, you’ll learn how to delete a non-empty directory recursively — delete all its files and sub-folders.

Java provides multiple methods to delete a directory. However, the directory must be emptied before we delete it. To remove all contents of a particular directory programmatically, we need to use recursion as explained below:

  1. List all contents (files & sub-folders) of the directory to be deleted.
  2. Delete all regular files of the current directory (exist from recursion).
  3. For each sub-folder of the current directory, go back to step 1 (recursive step).
  4. Delete the directory.

Let us look at different ways to implement the above simple recursive algorithm.

In Java 8 or higher, you can use Files.walk() from NIO API (classes in java.nio.* package) to recursively delete a non-empty directory. This method returns a Stream that can be used to delete all files and sub-folders as shown below:

try  // create a stream StreamPath> files = Files.walk(Paths.get("dir")); // delete directory including files and sub-folders files.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::deleteOnExit); // close the stream files.close(); > catch (IOException ex)  ex.printStackTrace(); > 

In the above example, Files.walk() returns a Stream of Path . We sorted it in the reverse order to place the paths indicating the contents of directories before directories itself. Afterward, it maps Path to File and deletes each File .

To delete a non-empty directory using Java legacy I/O API, we need to manually write a recursive function to implement the above algorithm. Here is how it looks like:

public void deleteDir(File dir)  File[] files = dir.listFiles(); if(files != null)  for (final File file : files)  deleteDir(file); > > dir.delete(); > 

As you can see above, we are using File.listFiles() method to list all files and sub-directories in the directory. For each file, we recursively call deleteDir() method. In the end, we delete the directory using File.delete() . Now you can call the above method as follows:

File dir = new File("dir"); deleteDir(dir); 

The Apache Commons IO library provides FileUtils.deleteDirectory() method to delete a directory recursively including all files and sub-directories:

try  // directory path File dir = new File("dir"); // delete directory recursively FileUtils.deleteDirectory(dir); > catch (IOException ex)  ex.printStackTrace(); > 
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>2.6version> dependency> 
implementation 'commons-io:commons-io:2.6' 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Delete Files in a Directory Using Java

Delete Files in a Directory Using Java

  1. Delete Files in a Directory Using delete() of File Class in Java
  2. Delete Files in a Directory Using Java 8 Streams and NIO2
  3. Delete Files in a Directory Using Apache Common IO
  4. Conclusion

In this article, we will learn how to delete files present inside the folder without deleting the folder itself.

There are multiple ways to do this. Let’s look at them one by one.

Delete Files in a Directory Using delete() of File Class in Java

In Java, we have the java.io.File class, which contains a method called delete() used to delete files and empty directories.

Let’s assume in our system’s D: drive a directory with a name as test exists, and let’s say it contains some text files and some sub-folders. Now, let’s see how to delete this using the delete() method.

import java.io.File;  public class Example   public static void main(String[] args)    String path = "D:\\test";  File obj = new File(path);   for (File temp: Objects.requireNonNull(obj.listFiles()))   if (!temp.isDirectory())   temp.delete();  >  >   > > 

When the above code is executed, we can see that all the files inside the test are deleted, but the main folder test and the sub-folders are untouched.

In the above, we have created a string variable that stores the path of the directory. Then we used this path to create our file object obj .

Then we used the listFiles() method to list the contents present at that path.

Using the if condition, we check if it’s a directory or a file. If it is a file, we delete it; else, we do nothing.

Delete Files in a Directory Using Java 8 Streams and NIO2

In this method, we can use the Files.walk(Path) method that returns Stream , which contains all the files and sub-folders present in that path .

Then we check if it’s a directory or a file using the if condition. If it is a file, we delete it; else, we do nothing.

import java.io.*; import java.nio.file.*; import java.util.*;  public class Demo   public static void main(String[] args)throws IOException    Path path = Paths.get("D:\\test");   Files.walk(path).sorted(Comparator.reverseOrder())  .forEach(data->  try    if(!Files.isDirectory(data))   System.out.println("deleting: " + data);  Files.delete(data);  >  >catch(IOException obj)    obj.printStackTrace();  >  >);  > > 
deleting: D:\test\subfolder 2\file4.txt deleting: D:\test\subfolder 1\file3.txt deleting: D:\test\file2.txt deleting: D:\test\file1.txt 

When the above code is executed, it deletes all the files of the directory and sub-directory files in a Depth First Search fashion.

We can observe that the directory test and the sub-directories subfolder 1 and subfolder 2 remained intact.

Delete Files in a Directory Using Apache Common IO

So far, all the methods we have seen are plain old Java methods that use some concepts of recursion along with file and stream methods. But we can use Apache Common IO FileUtils.cleanDirectory() to recursively delete all the files and the sub-directories within the main directory without deleting the main directory itself.

The main advantage of using this over primitive Java methods is that the line of codes (LOC) is significantly less, making it an easy and more efficient way of writing.

To use Apache common IO, we must first add the dependencies in our pom.xml file.

  commons-io  commons-io  2.11.0  
import java.io.*; import org.apache.commons.io.FileUtils;  public class Example   public static void main(String[] args)throws IOException    String path = "D:\\test";  File obj = new File(path);  FileUtils.cleanDirectory(obj);  > > 

Conclusion

This article has shown different ways of deleting directories using Java. We understood how to use the delete() method and Java 8 streams and how using Apache commons IO could be more efficient and time-saving where LOC (line of codes) greatly affects the performance of our project.

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

Related Article — Java File

Источник

Java I/O How to — Delete all files and directories under a folder recursively

We would like to know how to delete all files and directories under a folder recursively.

Answer

/*from ww w . j av a 2 s . c om*/ import java.io.File; import java.io.IOException; public class Main < /** * delete all files under this file and including this file * * @param f * @throws IOException */ public static void deleteAll(File f) throws IOException < recurse(f, new RecurseAction() < public void doFile(File file) throws IOException < file.delete(); if (file.exists()) < throw new IOException("Failed to delete " + file.getPath()); > > public void doBeforeFile(File f) < >public void doAfterFile(File f) < >>); > public static void recurse(File f, RecurseAction action) throws IOException < action.doBeforeFile(f); if (f.isDirectory()) < File[] files = f.listFiles(); if (files != null) < for (int i = 0; i < files.length; i++) < if (files[i].isDirectory()) < recurse(files[i], action); >else < action.doFile(files[i]); >> > > action.doFile(f); > > interface RecurseAction < /** * @param file * @throws IOException */ void doFile(File file) throws IOException; /** * @param f */ void doBeforeFile(File f); /** * @param f */ void doAfterFile(File f); >
/* w ww . jav a2 s . c o m*/ /* * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006. * * Licensed under the Aduna BSD-style license. */ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main < /** * Deletes the specified diretory and any files and directories in it * recursively. * * @param dir The directory to remove. * @throws IOException If the directory could not be removed. */ public static void deleteDir(File dir) throws IOException < if (!dir.isDirectory()) < throw new IOException("Not a directory " + dir); > File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) < File file = files[i]; if (file.isDirectory()) < deleteDir(file); >else < boolean deleted = file.delete(); if (!deleted) < throw new IOException("Unable to delete file" + file); > > > dir.delete(); > >

java2s.com | © Demo Source and Support. All rights reserved.

Источник

Читайте также:  Hello World
Оцените статью