Spring Framework: load resources sorted by filename


Sometimes it is necessary to load classpath-resources for working with them (e. g. loading data). In this case, the additional requirement was to provide the resources in a sorted way. The implementation is done with the ResourcePatternResolver from Spring Framework.

Custom resource comparator for sorting the resources:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import java.util.Comparator;
 
public class ResourceComparator implements Comparator<Resource> {
    @Override
    public int compare(Resource r1, Resource r2) {
        if (r1 == null || r2 == null
                || StringUtils.isEmpty(r1.getFilename()) || StringUtils.isEmpty(r2.getFilename()) ) {
            return 0;
        }
 
        final char v1[] = r1.getFilename().toCharArray();
        final char v2[] = r2.getFilename().toCharArray();
 
        int len1 = v1.length;
        int len2 = v2.length;
        int lim = Math.min(len1, len2);
 
        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }
}

The class loading the resources and providing them in a sorted way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.util.Arrays;
 
public class ResourceLoader {
	private static final String PATTERN = "resource*.xml";
 
	public void loadResources() {
		ClassLoader cl = this.getClass().getClassLoader();
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
		Resource[] resources = resolver.getResources("classpath*:" + PATTERN);
		Arrays.sort(resources, new ResourceComparator());
 
		for (Resource resource : resources) {
			//process the resources
		}
	}
}