# apache.commons.io Dateien suchen mit FileFilter



## Daniel Traub (30. November 2010)

Hallo,

in diesem Beitrag soll es um die FileFilter der apache.commons gehen. Die API findet ihr unter http://commons.apache.org/io/api-1.4/org/apache/commons/io/filefilter/package-summary.html. Es gibt eigentlich für alle erdenklichen Situationen einen passenden Filter, und mehrere Filter können kombiniert werden. Damit bietet apache.commons ein mächtiges Werkzeug zur Deteisuche (und auch für alles andere, was die Arbeit mit Dateien betrifft).Ich stelle hier eine kleine GUI vor, welche das Dateisystem nach verschiedenen Kriterien durchsucht und die Treffer zur weiteren Bearbeitung in einer List<File> speichert. Wenn das nicht reicht, könnte man die verschiedenen Filter natürlich auch noch in einen NotFileFilter stecken, um bestimmte Dateien auszuschliessen.



```
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.apache.commons.io.filefilter.AgeFileFilter;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SizeFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

/**
 * 
 * @author Daniel Traub
 * 
 */
public class SearchGUI {
    static JTextField rootTF, containsTF, containsNotTF, suffixTF, prefixTF,
            minDateTF, maxDateTF;

    static JCheckBox hiddenCB, recursiveCB;

    static JButton searchBtn, rootBtn, checkBtn;

    static JFormattedTextField minSizeTF, maxSizeTF;

    static File root;

    static JLabel rootLbl, containsLbl, containsNotLbl, suffixLbl, prefixLbl,
            minDateLbl, maxDateLbl, minSizeLbl, maxSizeLbl, hiddenLbl,
            recursiveLbl;

    static Boolean tcArtist, tcTitle, tcAlbum, tcTrack, tcDisc, tcYear,
            tcComposer;

    public static void main(String args[]) {

        initGUI();

    }

    /**
     * Initiate GUI
     */
    private static void initGUI() {

        // get System look&feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // init components
        final JFrame frame = new JFrame("Search Files");
        JPanel panel = new JPanel();
        rootTF = new JTextField(20);
        containsTF = new JTextField(20);
        containsNotTF = new JTextField(20);
        minSizeTF = new JFormattedTextField(NumberFormat.getInstance());
        maxSizeTF = new JFormattedTextField(NumberFormat.getInstance());
        suffixTF = new JTextField(10);
        prefixTF = new JTextField(10);
        minDateTF = new JTextField(10);
        maxDateTF = new JTextField(10);
        hiddenCB = new JCheckBox("search hidden");
        recursiveCB = new JCheckBox("search subfolders");
        searchBtn = new JButton("search");
        searchBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                SearchGUI.initSearch();
            }
        });
        rootBtn = new JButton("select Folder");
        rootBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fc.showOpenDialog(frame);
                root = fc.getSelectedFile();
                rootTF.setText(root.getAbsolutePath());
            }

        });
        rootLbl = new JLabel("search in: ", JLabel.CENTER);
        containsLbl = new JLabel("Filename contains: ", JLabel.CENTER);
        containsNotLbl = new JLabel(" Filename contains not", JLabel.CENTER);
        minSizeLbl = new JLabel("min. Size", JLabel.CENTER);
        maxSizeLbl = new JLabel("max. Size", JLabel.CENTER);
        suffixLbl = new JLabel("Filetypes", JLabel.CENTER);
        prefixLbl = new JLabel("begins with", JLabel.CENTER);
        minDateLbl = new JLabel("min. Date", JLabel.CENTER);
        maxDateLbl = new JLabel("max Date", JLabel.CENTER);
        hiddenLbl = new JLabel("search hidden files", JLabel.CENTER);
        recursiveLbl = new JLabel("search subfolders", JLabel.CENTER);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = frame.getContentPane();
        GridBagLayout gbl = new GridBagLayout();
        c.setLayout(gbl);

        /*
         * add components to gridbaglayout
         */
        // addComponent(c, gbl,,,,,,,);
        // addComponent(c, gbl,,,,, 1, 0.0, 0.0);
        // x y w h wx wy
        addComponent(c, gbl, rootLbl, 0, 0, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, rootBtn, 1, 0, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, rootTF, 0, 1, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, containsLbl, 0, 2, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, containsTF, 0, 3, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, containsNotLbl, 0, 4, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, containsNotTF, 0, 5, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, minSizeLbl, 0, 6, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, maxSizeLbl, 1, 6, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, minSizeTF, 0, 7, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, maxSizeTF, 1, 7, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, suffixLbl, 0, 8, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, suffixTF, 0, 9, 2, 1, 1.0, 0.0);
        addComponent(c, gbl, minDateLbl, 0, 10, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, maxDateLbl, 1, 10, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, minDateTF, 0, 11, 1, 1, 1.0, 0.0);
        addComponent(c, gbl, maxDateTF, 1, 11, 1, 1, 1.0, 0.0);
        // addComponent(c, gbl, hiddenLbl, 0, 12, 1, 1, 0, 0);
        // addComponent(c, gbl, recursiveLbl, 1, 12, 1, 1, 0, 0);
        addComponent(c, gbl, hiddenCB, 0, 12, 1, 1, 0, 0);
        addComponent(c, gbl, recursiveCB, 1, 12, 1, 1, 0, 0);
        addComponent(c, gbl, searchBtn, 0, 13, 2, 1, 1.0, 0.0);

        root = new File(System.getProperty("user.home"));
        rootTF.setText(root.toString());
        recursiveCB.setSelected(true);

        setToolTips();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    /**
     * set tooltips
     */
    private static void setToolTips() {

        String rootTT = "Folder to search in";
        String containsTT = "<html>Filenames containing this wildcard argument(s)<br>"
                + "You can seperate multiple wildcards via ','<br>"
                + "example: \"*java*, *class*, *src*\"";
        String containsNotTT = "Filenames not containing this wildcard argument(s)";
        String minSizeTT = "Min. filesize in MB";
        String maxSizeTT = "Max. filesize in MB";
        String suffixTT = "<html>Files didn't ends with this extension(s) will be ignored.<br>"
                + "Examlpe: \".java,class,.dat, sh ,exe<br>"
                + "Note the spaces above will be Ignored.";
        String prefixTT = "File begins with one of this prefixes, seperated by ','.";
        String minDateTT = "<html>Files newer than this date<br>" + "Format: ";
        String maxDateTT = "<html>Files must be older than this Date<br>"
                + "Date format: ";
        String hiddenTT = "Include hidden Files.";
        String recursiveTT = "Search subfolders.";

        rootLbl.setToolTipText(rootTT);
        rootTF.setToolTipText(rootTT);
        containsLbl.setToolTipText(containsTT);
        containsTF.setToolTipText(containsTT);
        containsNotLbl.setToolTipText(containsNotTT);
        containsNotTF.setToolTipText(containsNotTT);
        minSizeLbl.setToolTipText(minSizeTT);
        minSizeTF.setToolTipText(minSizeTT);
        maxSizeLbl.setToolTipText(maxSizeTT);
        maxSizeTF.setToolTipText(maxSizeTT);
        prefixLbl.setToolTipText(prefixTT);
        prefixTF.setToolTipText(prefixTT);
        minDateLbl.setToolTipText(minDateTT);
        minDateTF.setToolTipText(minDateTT);
        maxDateLbl.setToolTipText(maxDateTT);
        maxDateTF.setToolTipText(maxDateTT);
        hiddenCB.setToolTipText(hiddenTT);
        recursiveCB.setToolTipText(recursiveTT);
        suffixLbl.setToolTipText(suffixTT);
        suffixTF.setToolTipText(suffixTT);

    }

    /**
     * GridBagLayout
     * 
     * @param cont
     * @param gbl
     * @param c
     * @param x
     * @param y
     * @param width
     * @param height
     * @param weightx
     * @param weighty
     */
    static void addComponent(Container cont, GridBagLayout gbl, Component c,
            int x, int y, int width, int height, double weightx, double weighty) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = height;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbl.setConstraints(c, gbc);
        cont.add(c);
    }

    /**
     * Parse userinput to filefilters
     */
    public static void initSearch() {
        // set DateFormat
        SimpleDateFormat sdf = new SimpleDateFormat("yyy.MM.dd"); // HH.mm.ss");
        root = new File(rootTF.getText());
        // split userinput to make multiple filters
        String[] contains = containsTF.getText().replaceAll(" ", "").split(",");
        String[] containsNot = containsNotTF.getText().replaceAll(" ", "")
                .split(",");
        String[] suffix = suffixTF.getText().replaceAll(" ", "").split(",");
        Date minDate = null;
        Date maxDate = null;
        AgeFileFilter minDateFilter = null;
        AgeFileFilter maxDateFilter = null;
        if (minDateTF.getText().length() > 0) {
            // parse Date
            try {
                minDate = sdf.parse(minDateTF.getText());
                minDateFilter = new AgeFileFilter(minDate, false);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (maxDateTF.getText().length() > 0) {
            try {
                maxDate = sdf.parse(maxDateTF.getText());
                maxDateFilter = new AgeFileFilter(maxDate, true);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Boolean hidden = hiddenCB.isSelected();
        Boolean recursive = recursiveCB.isSelected();

        Long minSize = 0l;
        if (minSizeTF.getText().replaceAll(" ", "").length() > 0) {
            minSize = Long.valueOf(minSizeTF.getText()) * 1024l * 1024l;
        }
        Long maxSize = 1l * 1024l * 1024l * 1024l * 1024l * 1024l;
        if (maxSizeTF.getText().replaceAll(" ", "").length() > 0) {
            maxSize = Long.valueOf(maxSizeTF.getText());
        }

        WildcardFileFilter containsFilter = new WildcardFileFilter(contains);
        WildcardFileFilter containsNotFilter = new WildcardFileFilter(
                containsNot);
        SizeFileFilter sizeMinFilter = new SizeFileFilter(minSize);
        SizeFileFilter sizeMaxFilter = new SizeFileFilter(maxSize, false);
        SuffixFileFilter suffixFilter = new SuffixFileFilter(suffix);

        List<IOFileFilter> filterList = new ArrayList<IOFileFilter>();
        System.out.println(containsFilter);

        // check filters
        if (containsFilter.toString().length() > "WildcardFileFilter()"
                .length()) {
            filterList.add(containsFilter);
        }
        if (containsNotFilter.toString().length() > "WildcardFileFilter()"
                .length()) {
            filterList.add(containsNotFilter);
        }
        if (sizeMinFilter != null) {
            filterList.add(sizeMinFilter);
        }
        if (sizeMaxFilter != null) {
            filterList.add(sizeMaxFilter);
        }
        if (suffixFilter.toString().length() > "SuffixFileFilter()".length()) {
            filterList.add(suffixFilter);
        }
        if (minDateFilter != null) {
            filterList.add(minDateFilter);
        }
        if (maxDateFilter != null) {
            filterList.add(maxDateFilter);
        }

        // add filters
        AndFileFilter fileFilter = new AndFileFilter(filterList);

        // perform search
        BuildFileTable.search(root, fileFilter, hidden, recursive);

    }

    protected static void getRoot() {
    }

}
```


```
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;

/**
 * Adds all files that match the search criteria to a Listy<file>
 * 
 * @author Daniel Traub
 * 
 */
public class BuildFileList {
    static List<File> fileList;

    public static void search(File root, IOFileFilter fileFilter,
            Boolean hidden, Boolean recursive) {

        fileList = new ArrayList<File>();
        System.out.println(fileFilter);

        try {
            if (recursive == true) {
                if (hidden == true) {
                    Collection files = FileUtils.listFiles(root, fileFilter,
                            TrueFileFilter.TRUE);
                    for (Iterator iterator = files.iterator(); iterator
                            .hasNext();) {
                        File file = (File) iterator.next();
                        fileList.add(file);
                        // System.out.println("FILE="+file);
                    }
                } else {
                    Collection files = FileUtils.listFiles(root,
                            new AndFileFilter(HiddenFileFilter.VISIBLE,
                                    fileFilter), TrueFileFilter.TRUE);
                    for (Iterator iterator = files.iterator(); iterator
                            .hasNext();) {
                        File file = (File) iterator.next();
                        fileList.add(file);
                    }
                }
            } else {
                if (hidden == true) {
                    Collection files = FileUtils.listFiles(root, fileFilter,
                            null);
                    for (Iterator iterator = files.iterator(); iterator
                            .hasNext();) {
                        File file = (File) iterator.next();
                        fileList.add(file);
                    }
                } else {
                    Collection files = FileUtils.listFiles(root,
                            new AndFileFilter(HiddenFileFilter.VISIBLE,
                                    fileFilter), null);
                    for (Iterator iterator = files.iterator(); iterator
                            .hasNext();) {
                        File file = (File) iterator.next();
                        fileList.add(file);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("\tFolgende Dateien wurden gefunden:\n\n");
        for (int i = 0; i < fileList.size(); i++) {
            System.out.println(fileList.get(i));
        }
    }
}
```

Vielen Dank an Thomas Darimont, dessen Engagement hier im forum mir den Einstieg in Java sehr erleichtert hat!

Daniel Traub


----------



## Thomas Darimont (30. November 2010)

Hallo,



> Vielen Dank an Thomas Darimont, dessen Engagement hier im forum mir den Einstieg in Java sehr erleichtert hat!



Danke danke  Freut mich immer wenn ich helfen kann 


Gruß Tom


----------

