File files[] = rootDir.listFiles(new FileFilter() {
public boolean accept(File file) {
if (file.isDirectory())
return true;
String name = file.getName().toLowerCase();
if (name.endsWith(".zip") || name.endsWith(".jar")
|| name.endsWith(".z") || name.endsWith(".gz")
|| name.endsWith(".tar") || name.endsWith(".bz2")
|| name.endsWith(".bz"))
return true;
return false;
}
});
As you can see, the code is dirty with "||"
Do you know how to make it better?
FileFilter is an abstract class used by JFileChooser for filtering the set of files shown to the user. See FileNameExtensionFilter for an implementation that filters using the file name extension. A FileFilter can be set on a JFileChooser to keep unwanted files from appearing in the directory listing.
public final class FileNameExtensionFilter extends FileFilter. An implementation of FileFilter that filters using a specified set of extensions. The extension for a file is the portion of the file name after the last ".". Files whose name does not contain a "." have no file name extension.
With Java 6 or above, this is a perfect case for a FileNameExtensionFilter
... except that it extends javax.swing.filechooser.FileFilter
instead of implementing java.io.FileFilter
.
But it is trivial to write a wrapper for it:
File[] files = rootDir.listFiles(new FileFilter() {
private final FileNameExtensionFilter filter =
new FileNameExtensionFilter("Compressed files",
"zip", "jar", "z", "gz", "tar", "bz2", "bz");
public boolean accept(File file) {
return filter.accept(file);
}
});
Why not use regular expressions?
static final Pattern p = Pattern.compile("\\.(zip|jar|z|gz)$");
and then return p.matcher(name).find();
Some pseudocode solutions:
suffixes = [".tar", ".zip", ".jpg"]
for suffix in suffixes:
if name.endsWith(suffix):
return True
suffixes = [".tar", ".zip", ".jpg"]
nameSuffix = name.getSuffix()
if nameSuffix in suffixes:
return True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With