KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > monitorenter > gui > chart > io > FileFilterExtensions


1 /*
2  *
3  * FileFilterExtensions.java, a FileFilter implementation that
4  * filters files by their extension.
5  * Copyright (C) Achim Westermann, created on 01.07.2004, 12:18:29
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20  *
21  * If you modify or optimize the code in a useful way please let me know.
22  * Achim.Westermann@gmx.de
23  *
24  */

25 package info.monitorenter.gui.chart.io;
26
27 import java.io.File JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31
32 import javax.swing.filechooser.FileFilter JavaDoc;
33 import javax.swing.filechooser.FileSystemView JavaDoc;
34
35 /**
36  * <p>
37  * Configureable implementation of {@link javax.swing.filechooser.FileFilter}
38  * that filters files by their extension (e.g.: ".txt").
39  * </p>
40  * <p>
41  * The extension Strings are provided to the constructor (no configuration of
42  * initialized instance provided yet) and have to be the sole extension without
43  * the dot.
44  * </p>
45  * <p>
46  * This class is most often used to configure {@link javax.swing.JFileChooser}
47  * dialogs. Therefore it accepts all directories to allow browsing.
48  * </p>
49  * <h3>Example usage:</h3>
50  * <p>
51  *
52  * <code>
53  *
54  * ...
55  * JFileChooser fileChooser = new JFileChooser();
56  * FileFilter soundFileFilter = new FileFilterExtensions(new String[]{&quot;wav&quot;,&quot;mp3&quot;});
57  * fileChooser.setFileFilter(soundFileFilter);
58  * ...
59  *
60  * </code>
61  *
62  * </p>
63  *
64  * @author <a HREF="mailto:Achim.Westermann@gmx.de>Achim Westermann </a>
65  */

66 public final class FileFilterExtensions extends FileFilter JavaDoc implements INameFilter {
67   /** Filename extensions to filter for. */
68   private String JavaDoc[] m_extensions;
69
70   /** Flag for windows OS. */
71   private boolean m_isWindows = false;
72
73   /**
74    * Creates an instance that will accept files with the given extensions.
75    * <p>
76    *
77    * @param extensionsWithoutDot
78    * A String[] containing extension strings without the dot like:
79    * <nobr><code>new String[]{"bat","txt","dict"}</code> </nobr>.
80    * @throws IllegalArgumentException
81    * if the given extensions are inivalid.
82    */

83   public FileFilterExtensions(final String JavaDoc[] extensionsWithoutDot) throws IllegalArgumentException JavaDoc {
84     this.verify(extensionsWithoutDot);
85     this.m_extensions = extensionsWithoutDot;
86     this.m_isWindows = this.isWindows();
87   }
88
89   /**
90    * @see java.io.FileFilter#accept(java.io.File)
91    */

92   public boolean accept(final File JavaDoc pathname) {
93     if (pathname.isDirectory()) {
94       return true;
95     }
96     return acceptNoDirectory(pathname.getAbsolutePath());
97   }
98
99   /**
100    * @see INameFilter#accept(String)
101    */

102   public boolean accept(final String JavaDoc urlstring) {
103     if (isDirectory(urlstring)) {
104       return true;
105     }
106     return acceptNoDirectory(urlstring);
107   }
108
109   /**
110    * Accept method used for files.
111    * <p>
112    *
113    * @param noDirFileNoURL
114    * the path to the file.
115    * @return true if the file denoted by the given path is accepted.
116    */

117   private boolean acceptNoDirectory(final String JavaDoc noDirFileNoURL) {
118     boolean ret = false;
119     // search for extension without dot.
120
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(noDirFileNoURL, ".");
121     // a dot, because verify will not allow these
122
String JavaDoc extension = "no.txt";
123     // tokens: won't accept, if no extension in
124
// pathname.
125
while (tokenizer.hasMoreElements()) {
126       extension = tokenizer.nextToken();
127     }
128     for (int i = this.m_extensions.length - 1; i >= 0; i--) {
129       if (this.m_extensions[i].equals(extension)) {
130         ret = true;
131         break;
132       }
133     }
134     return ret;
135   }
136
137   /**
138    * @see javax.swing.filechooser.FileFilter#getDescription()
139    */

140   public String JavaDoc getDescription() {
141     StringBuffer JavaDoc ret = new StringBuffer JavaDoc();
142     int len = this.m_extensions.length;
143     for (int i = 0; i < len; i++) {
144       ret.append("*.").append(this.m_extensions[i]);
145       if (i < (len - 1)) {
146         ret.append(",");
147       }
148     }
149     return ret.toString();
150   }
151
152   /**
153    * Returns true if the given String denotes a directory.
154    * <p>
155    *
156    * @param urlstring
157    * the url format String pointing to a file.
158    * @return true if the given String denotes a directory.
159    */

160   private boolean isDirectory(final String JavaDoc urlstring) {
161     boolean ret = false;
162     boolean isURL = false;
163     try {
164       // try, if URL (expensive):
165
new URL JavaDoc(urlstring);
166       isURL = true;
167     } catch (MalformedURLException JavaDoc e) {
168       // nop.
169
}
170
171     int lastDot = urlstring.lastIndexOf('.');
172     int lastSeparator;
173     // Could be minimized but is more talking this way.
174
if (isURL) {
175       lastSeparator = urlstring.lastIndexOf('/');
176     } else {
177       if (this.m_isWindows) {
178         lastSeparator = urlstring.lastIndexOf('\\');
179       } else {
180         lastSeparator = urlstring.lastIndexOf('/');
181       }
182     }
183
184     if (lastSeparator == -1) {
185       if (lastDot == -1) {
186         // top host without a path.
187
ret = true;
188       } else {
189         ret = false;
190       }
191     } else {
192       if (lastDot == -1) {
193         ret = true;
194       } else if (lastDot > (lastSeparator + 1)) {
195         ret = false;
196       } else {
197         ret = true;
198       }
199     }
200     return ret;
201   }
202
203   /**
204    * Needed for {@link #isDirectory(String)}: We cannot use
205    * {@link System#getProperty(java.lang.String)} to determine file separators
206    * in applet context. That would possibly throw an SecurityAccessException.
207    * <p>
208    *
209    * @return true if current OS is windows.
210    */

211   private boolean isWindows() {
212     boolean ret = false;
213     File JavaDoc[] roots = FileSystemView.getFileSystemView().getRoots();
214     for (int i = 0; i < roots.length; i++) {
215       if (roots[i].getAbsolutePath().indexOf(':') != -1) {
216         ret = true;
217         break;
218       }
219     }
220     return ret;
221   }
222
223   /**
224    * Verifies the given extensions for valid format.
225    * <p>
226    *
227    * @param extensions
228    * The array with the Strings of extensions.
229    * @throws IllegalArgumentException
230    * If a String of the array is null or contains a dot ('.').
231    */

232   private void verify(final String JavaDoc[] extensions) throws IllegalArgumentException JavaDoc {
233     String JavaDoc current;
234     StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
235     for (int i = extensions.length - 1; i >= 0; i--) {
236       current = extensions[i];
237       if (current == null) {
238         msg.append("Extension at index " + i + " is null!\n");
239       } else if (current.indexOf('.') != -1) {
240         msg.append("Extension \"" + current + "\" contains a dot!\n");
241       }
242     }
243     if (msg.length() > 0) {
244       throw new IllegalArgumentException JavaDoc(msg.toString());
245     }
246   }
247 }
248
Popular Tags