1 // ========================================================================
2 // Copyright (c) Webtide LLC
3 // ------------------------------------------------------------------------
4 // All rights reserved. This program and the accompanying materials
5 // are made available under the terms of the Eclipse Public License v1.0
6 // and Apache License v2.0 which accompanies this distribution.
7 //
8 // The Eclipse Public License is available at
9 // http://www.eclipse.org/legal/epl-v10.html
10 //
11 // The Apache License v2.0 is available at
12 // http://www.apache.org/licenses/LICENSE-2.0.txt
13 //
14 // You may elect to redistribute this code under either of these licenses.
15 // ========================================================================
16 package org.eclipse.jetty.start;
17
18 import java.io.File;
19 import java.text.CollationKey;
20 import java.text.Collator;
21 import java.util.Comparator;
22
23 /**
24 * Smart comparator for filenames, with natural language sorting, and files sorted before sub directories.
25 */
26 public class FilenameComparator implements Comparator<File>
27 {
28 public static final FilenameComparator INSTANCE = new FilenameComparator();
29 private Collator collator = Collator.getInstance();
30
31 public int compare(File o1, File o2)
32 {
33 if (o1.isFile())
34 {
35 if (o2.isFile())
36 {
37 CollationKey key1 = toKey(o1);
38 CollationKey key2 = toKey(o2);
39 return key1.compareTo(key2);
40 }
41 else
42 {
43 // Push o2 directories below o1 files
44 return -1;
45 }
46 }
47 else
48 {
49 if (o2.isDirectory())
50 {
51 CollationKey key1 = toKey(o1);
52 CollationKey key2 = toKey(o2);
53 return key1.compareTo(key2);
54 }
55 else
56 {
57 // Push o2 files above o1 directories
58 return 1;
59 }
60 }
61 }
62
63 private CollationKey toKey(File f)
64 {
65 return collator.getCollationKey(f.getAbsolutePath());
66 }
67 }