View Javadoc

1   package fr.ove.utils;
2   
3   import javax.swing.filechooser.FileFilter;
4   import java.io.File;
5   
6   /***
7   * A file filter for the specified extension.
8   */
9   public class GenericFileFilter extends FileFilter {
10      /***
11      * The type of files to filter.
12      */
13      private String type;
14      
15      /***
16      * The extension of files to filter.
17      */
18      private String extension;
19      
20      /***
21      * The default constructor. Builds a text files (with a txt extension) filter.
22      */
23      public GenericFileFilter() {
24          this("Text", "txt");
25      }
26      
27      /***
28      * The constructor.
29      * @param type the file type (e.g. Text, JPEG, etc).
30      * @param extension the file extension (e.g. txt, jpeg, etc).
31      */
32      public GenericFileFilter(String type, String extension) {
33          this.type = type;
34          this.extension = extension;
35      }
36      
37      /***
38      * Sets the file type.
39      * @param type the file type (e.g. Text, JPEG, etc).
40      */
41      public void setType(String type) {
42          this.type = type;
43      }
44      
45      /***
46      * Gets the file type.
47      */
48      public String getType() {
49          return type;
50      }
51      
52      /***
53      * Sets the file extension.
54      * @param extension the file extension (e.g. txt, jpeg, etc);
55      */
56      public void setExtension(String extension) {
57          this.extension = extension;
58      }
59      
60      /***
61      * Gets the file extension.
62      */
63      public String getExtension() {
64          return extension;
65      }
66      
67      /***
68      * Whether the given file is accepted by this filter.
69      * @param file the given file.
70      */
71      public boolean accept(File file) {
72          boolean accept = file.isDirectory();
73          
74          if (!accept) {
75              String suffix = getSuffix(file);
76              if (suffix != null)
77                  accept = suffix.equals(extension);
78          }
79          
80          return accept;
81      }
82      
83      /***
84      * The description of this filter.
85      */
86      public String getDescription() {
87          return type + " Files (*." + extension + ")";
88      }
89      
90      /***
91      * Gets the suffix of the specified file.
92      * @param file the file.
93      */
94      private String getSuffix(File file) {
95          String path = file.getPath();
96          String suffix = null;
97          int index = path.lastIndexOf('.');
98          if ((index > 0) && (index < (path.length() - 1)))
99              suffix = path.substring(index + 1).toLowerCase();
100             
101         return suffix;
102     }
103 }