public static void keepDirWithinSize(File dir, int size) {
        if (!dir.isDirectory()) return;
        File[] files = dir.listFiles();
        if (files == null) return;

        long dirSize = countDirSize(dir);

        if (dirSize < size) return;

        Arrays.sort(files, new FileDateComparator());
        int count = files.length;
        File file;
        for (int i = 0; i < count; i++) {
            file = files[i];
            long currentSize = file.isDirectory() ? 0l : file.length();
            if (file.delete()) {
                dirSize -= currentSize;
                if (dirSize < size) break;
            }
        }
    }