SoFunction
Updated on 2025-04-13

Java calls Oss JDk to delete all files in the specified directory

1. Introduce dependencies

<dependency>
    <groupId></groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.16.1</version>
</dependency>

2. Method

/**
	  * Delete multiple files under the specified prefix or directory
	  *
	  * @param prefix Delete directory
	  */
	public void deletePathFileList(String prefix) {
		OSS ossClient = null;
		try {
            //Encapsulate creating Oss instance			CredentialsProvider credentialsProvider = new DefaultCredentialProvider(access_key, secret_key);
			ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
			(SignVersion.V4);
			ossClient = ().endpoint(endpoint).credentialsProvider(credentialsProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();
            // List all files containing the specified prefix and delete them.			String nextMarker = null;
			ObjectListing objectListing;
			do {
				ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket).withPrefix(prefix).withMarker(nextMarker);
 
				objectListing = (listObjectsRequest);
				if (!().isEmpty()) {
					List&lt;String&gt; keys = new ArrayList&lt;&gt;();
					for (OSSObjectSummary s : ()) {
						(());
					}
					DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket).withKeys(keys).withEncodingType("url");
					DeleteObjectsResult deleteObjectsResult = (deleteObjectsRequest);
					List&lt;String&gt; deletedObjects = ();
					for (String obj : deletedObjects) {
						String deleteObj = (obj, "UTF-8");
						(deleteObj);
					}
				}
				nextMarker = ();
			} while (());
		} catch (Exception e) {
			("Alibaba Cloud deletes multiple files under specified prefix or directory exception:{}", ());
		} finally {
			if (ossClient != null) {
				();
			}
		}
	}

3. Supplementary method

1. Use FileUtils class

The FileUtils class from Apache Commons IO provides several convenient file manipulation utilities. You can use the() method to recursively delete all files and subdirectories in a directory without deleting the directory itself.

import ;
import ;
import ; 
public class Main {
    public static void main(String[] args) throws IOException {
        File directory = new File("/path/to/dir");
        (directory);
    }
}

To recursively delete the directory and everything in it, you can use the() method.

import ;
import ;
import ; 
public class Main {
    public static void main(String[] args) throws IOException {
        File directory = new File("/path/to/dir");
        (directory);
    }
}

Alternatively, you can use the() method to delete one directory and all subdirectories.

import ;
import ;
import ;
public class Main {
    public static void main(String[] args) throws IOException {
        File directory = new File("/path/to/dir");
        (directory);
    }
}

2. Use the () method

This() method deletes a file or directory represented by the specified path name. There are many ways to conditionally delete files and subdirectories in the directory that uses it.

For example, the following solution only deletes files in the home directory, and all subdirectories remain unchanged.

import ;
import ; 
public class Main {
    public static void main(String[] args) {
        File directory = new File("/path/to/dir"); 
        for (File file: (())) {
            if (!()) {
                ();
            }
        }
    }
}

If you are using Java 8 or later, you can use:

import ;
import ;
import ;
import ; 
public class Main {
    public static void deleteDirectory(File directory) {
        ((()))
                .filter((File::isDirectory))
                .forEach(File::delete);
    } 
    public static void main(String[] args) {
        File directory = new File("/path/to/dir");
        deleteDirectory(directory);
    }
}

You can easily extend the solution to recursively delete all files and subdirectories in the directory. Note that () You can use this method to delete the directory if and only if the directory is empty.

import ;
import ; 
public class Main {
    public static void deleteDirectory(File directory) {
        for (File file: (())) {
            if (()) {
                deleteDirectory(file);
            } else {
                ();
            }
        }
    } 
    public static void main(String[] args) {
        File directory = new File("/path/to/dir");
        deleteDirectory(directory);
    }
}

This is the version that uses the Stream API. It takes advantage of the() method and deletes all files and subdirectories in the directory as well as the directory itself.

import ;
import ;
import ;
import ;
import ; 
public class Main {
    public static void deleteDirectory(Path directory) throws IOException {
        (directory)
                .sorted(())
                .map(Path::toFile)
                .forEach(File::delete);
    } 
    public static void main(String[] args) throws IOException {
        Path directory = ("/path/to/dir");
        deleteDirectory(directory);
    }
}

If you need to remove "File Only" from the directory and all its subdirectories, you can do the following:

import ;
import ;
import ;
import ; 
public class Main {
    public static void deleteDirectory(File directory) throws IOException {
        (())
                .filter(Files::isRegularFile)
                .map(Path::toFile)
                .forEach(File::delete);
    } 
    public static void main(String[] args) throws IOException {
        File directory = new File("/path/to/dir");
        deleteDirectory(directory);
    }
}

This is the article about Java calling Oss JDk to delete all files in a specified directory. For more related Java to delete files in a specified directory, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!