How to delete all temp files which created by createTempFile when exit an App in android?

前端 未结 7 2332
清酒与你
清酒与你 2021-02-07 15:06

I use the following code to create some temp files, and wrapped tem as inputsteam to send to client side.

I understand that the temp files can be deleted automatically b

7条回答
  •  盖世英雄少女心
    2021-02-07 15:27

    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 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 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
    

提交回复
热议问题