I ended up here looking for a way to remove temp files that I was creating for camera intents, I actually used a combination of Sridhar's answer and the cleanOldFiles
function from this answer
I was creating a new image file using createTempFile
and then adding that to
public static final HashSet<File> TEMP_FILES = new HashSet<>();
To iterate and remove from the set using the normal foreach loop was throwing a java.util.ConcurrentModificationException
so I updated the loop using an Iterator
more on iterators
Thought I'd post in case it helps someone else, thanks to Sridhar and ggrandes from the other post for the help.
public synchronized void cleanTempFiles(final int secondsOld) {
long now = (System.currentTimeMillis() / 1000);
for (Iterator<File> iterator = TEMP_FILES.iterator(); iterator.hasNext(); ) {
File f = iterator.next();
long expired = (f.lastModified() / 1000) + secondsOld;
if (now >= expired) {
Log.d(TAG, "Deleted file - \"" + f.getAbsolutePath() +"\"");
f.delete();
iterator.remove();
}
}
}
The function removes files older than a given time value in seconds and is called like
cleanTempFiles(3); // or however long