View Javadoc

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