Have you tried using adb shell commands?
One thing I tried that was helpful in deleting files in an Espresso test was executing ADB shell commands programmatically. Something like this:
(Kotlin sample)
val dir = Environment.getExternalStorageDirectory()
val file = File(dir.absolutePath
+ File.separator + directoryInExtStorageDir
+ File.separator + fileName)
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
"rm -f " + file.absolutePath)
Java would look something like this:
File dir = Environment.getExternalStorageDirectory()
File file = new File(dir.getAbsolutePath()
+ File.separator + directoryInExtStorageDir
+ File.separator + fileName)
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
"rm -f " + file.getAbsolutePath())
As for seeking out files of a specific type you can use the FilenameFilter or FileFilter interfaces for that. See this answer and this page for examples of how you can do this.
An example might look like this:
File dir = Environment.getExternalStorageDirectory();
File directory = new File(dir.getAbsolutePath()
+ File.separator + directoryInExtStorageDir);
List<File> filesToDelete = Arrays.asList(directory.listFiles((new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".ser");
}
})));
filesToDelete.forEach(file->{
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
"rm -f " + file.getAbsolutePath());
});
Hope that helped.