开发者

Finding all files of a particular naming scheme in java

Suppose I have a bunch of files named as such:

10011-1-chassis.EDRW
10011-2-front.EDRW
10011-3-rear.EDRW
20011-1-chassis.E开发者_如何学CDRW
20011-2-front.EDRW
20011-3-back.EASM
20011-3-cover.EASM

If I want only the 20011-x files then how would I list them all and then only the appropriate files so that I could present the filenames in a JOptionPane for the user to choose from a dropdown which file they were interested in?


Write a java.io.FilenameFilter that uses a regular expression that filters out unacceptable file names.

I recommend a regex because I'm assuming that you'll want to change the pattern dynamically. It's not overkill in that case. A hard-wired solution for the example you cite doesn't seem that useful to me. I'm assuming that users will want to tell you how they want to change the pattern by specifying it in your UI..


Use a JFileChooser instead of the JOptionPane with list. E.G.

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

class ShowPrefixedDrawings {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setMultiSelectionEnabled(true);
                chooser.setAcceptAllFileFilterUsed(false);
                String prefix = JOptionPane.showInputDialog(
                    null, "Prefix", "D");
                chooser.setFileFilter(
                    new PrefixDrawingFileFilter(prefix));
                int result = chooser.showOpenDialog(null);
                if (result==JFileChooser.APPROVE_OPTION) {
                    File[] files = chooser.getSelectedFiles();
                    for (File file : files) {
                        System.out.println(file.getName());
                    }
                }
                System.exit(0);
            }
        });
    }
}

class PrefixDrawingFileFilter extends FileFilter {

    String prefix;
    String[] suffixes = {"dwg", "dxf", "DWG", "DXF"};

    PrefixDrawingFileFilter(String prefix) {
        this.prefix = prefix;
    }

    public boolean accept(File f) {
        if (f.isDirectory()) return true;

        String name = f.getName();
        if ( name.startsWith(prefix) ) {
            for (String type : suffixes) {
                if (name.endsWith(type)) return true;
            }
        }

        return false;
    }

    public String getDescription() {
        return "eDrawings Viewer files starting with " + prefix;
    }
}


Use filename.startsWith ("20011-") as your filtering predicate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜