import java.io.FileFilter;
import java.io.File;public class JavaFileFilter implements FileFilter {
  public boolean accept(File aFile) {
    boolean resultValue = false;
    try {
      resultValue = aFile.getName().endsWith(".java");
    }catch(Exception e){}
    return resultValue;
  }
}

解决方案 »

  1.   

    这个帖子里有个很好的FileFilter例子:
    http://expert.csdn.net/Expert/topic/1410/1410007.xml?temp=.8511469
    具体的看看书吧
      

  2.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.filechooser.FileFilter;
    import java.io.File;public class Frame2 extends JFrame {
      JButton jButton1 = new JButton();  public static void main(String[] args){
        Frame2 f = new Frame2();
        f.setSize(250,200);
        f.show();
      }  public Frame2() {
        try {
          jbInit();
        } catch(Exception e) {
          e.printStackTrace();
        }  }  private void jbInit() throws Exception {
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jButton1_actionPerformed(e);
          }
        });
        this.getContentPane().add(jButton1, BorderLayout.NORTH);
        this.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });  }  void jButton1_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new Filter());
        chooser.showOpenDialog(this);
      }
    }class Filter extends FileFilter {  // Accept all directories and all gif, jpg, or tiff files.
      public boolean accept(File f) {
        if(f.isDirectory()) {
          return true;
        }    String extension = getExtension(f);
        if(extension != null) {
          if(extension.equals("gif") ||
             extension.equals("jpg")) {
            return true;
          } else {
            return false;
          }
        }    return false;
      }  public String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');    if(i > 0 && i < s.length() - 1) {
          ext = s.substring(i + 1).toLowerCase();
        }
        return ext;
      }  // The description of this filter
      public String getDescription() {
        return ".jpg .gif";
      }
    }
      

  3.   

    知道了,多谢!!!!!!!!可是当选文件,选取消的时候有异常发生啊!  咋解决啊?
    Exception occurred during event dispatching:java.lang.NullPointerException at java.io.FileInputStream.<init>(FileInputStream.java:95) at work.readfile.read(Frame2.java:72) at work.Frame2.jButton1_actionPerformed(Frame2.java:218) at work.Frame2$3.actionPerformed(Frame2.java:171) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1450) at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1504) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:378) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:250) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:216) at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:230) at java.awt.Component.processMouseEvent(Component.java:3715) at java.awt.Component.processEvent(Component.java:3544) at java.awt.Container.processEvent(Container.java:1164) at java.awt.Component.dispatchEventImpl(Component.java:2593) at java.awt.Container.dispatchEventImpl(Container.java:1213) at java.awt.Component.dispatchEvent(Component.java:2497) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2451) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125) at java.awt.Container.dispatchEventImpl(Container.java:1200) at java.awt.Window.dispatchEventImpl(Window.java:914) at java.awt.Component.dispatchEvent(Component.java:2497) at java.awt.EventQueue.dispatchEvent(EventQueue.java:339) at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
      

  4.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class MyFileWin extends JFrame
    { JFileChooser chooser=new JFileChooser();
     MyFileWin()
       { super("有文件选择器的窗口");
         chooser.showDialog(null,"打开");
         setSize(200,200);
         setVisible(true);
         getContentPane().add(new Label("ok"));
         addWindowListener(new WindowAdapter()
         {public void windowClosing(WindowEvent e)
           { System.exit(0);}} );
       }

    public class Example25_20
    {public static void main(String args[])
     {MyFileWin Win=new MyFileWin(); win.pack();  }
    }
      

  5.   

    这是 Sun 的例子 好好研究一下 :)import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;public class FileChooserDemo extends JFrame {
        static private final String newline = "\n";    public FileChooserDemo() {
            super("FileChooserDemo");        //Create the log first, because the action listeners
            //need to refer to it.
            final JTextArea log = new JTextArea(5,20);
            log.setMargin(new Insets(5,5,5,5));
            log.setEditable(false);
            JScrollPane logScrollPane = new JScrollPane(log);        //Create a file chooser
            final JFileChooser fc = new JFileChooser();        //Create the open button
            ImageIcon openIcon = new ImageIcon("images/open.gif");
            JButton openButton = new JButton("Open a File...", openIcon);
            openButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int returnVal = fc.showOpenDialog(FileChooserDemo.this);                if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        //this is where a real application would open the file.
                        log.append("Opening: " + file.getName() + "." + newline);
                    } else {
                        log.append("Open command cancelled by user." + newline);
                    }
                }
            });        //Create the save button
            ImageIcon saveIcon = new ImageIcon("images/save.gif");
            JButton saveButton = new JButton("Save a File...", saveIcon);
            saveButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int returnVal = fc.showSaveDialog(FileChooserDemo.this);                if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        //this is where a real application would save the file.
                        log.append("Saving: " + file.getName() + "." + newline);
                    } else {
                        log.append("Save command cancelled by user." + newline);
                    }
                }
            });        //For layout purposes, put the buttons in a separate panel
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(openButton);
            buttonPanel.add(saveButton);        //Explicitly set the focus sequence.
            openButton.setNextFocusableComponent(saveButton);
            saveButton.setNextFocusableComponent(openButton);        //Add the buttons and the log to the frame
            Container contentPane = getContentPane();
            contentPane.add(buttonPanel, BorderLayout.NORTH);
            contentPane.add(logScrollPane, BorderLayout.CENTER);
        }    public static void main(String[] args) {
            JFrame frame = new FileChooserDemo();        frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });        frame.pack();
            frame.setVisible(true);
        }
    }
      

  6.   

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    class opendisk extends JFrame implements ActionListener
    {
    opendisk()
    {
    super("open disk");
    JPanel pane=new JPanel();
    JButton open=new JButton("open");
    open.addActionListener(this);
    open.setActionCommand("open");
    pane.add(open);
    setContentPane(pane);
    show();
    }
    public static void main(String argu[])
    {
    opendisk od=new opendisk();
    od.pack();
    }
    public void actionPerformed(ActionEvent evt)
    {
    String cmd=evt.getActionCommand();
    if(cmd=="open")
    {
    JFileChooser JFileChooser1 = new JFileChooser("D:\\");//启动一个文件选择器
    if(JFileChooser1.APPROVE_OPTION==JFileChooser1.showOpenDialog(this))//如果文件选择完毕
    {
    openFile(JFileChooser1.getSelectedFile().getPath());//作为将来的接口
    String filepath=JFileChooser1.getSelectedFile().getPath();//获取被选择文件的路径
    System.out.println(filepath);//输出文件路径
    }
    }
    }
    void openFile(String fileName) 
        {
    try 
    {
    File file=new File(fileName);
    int size =(int)file.length();
    int chars_read=0;
    FileReader in=new FileReader(file);
    char[] data=new char[size];
    while(in.ready())
    {
    chars_read+=in.read(data,chars_read,size-chars_read);
    //read(目标数组、文件起始位置、文件结束位置)
    //返回读入的数据量
    }
    in.close();
    }
    catch(IOException e)
    {
    System.out.println(e.toString());
      }
    }}
      

  7.   

    我觉得你可以看一下JDK附带的DEMO,其中一个例子详细讲述了它们的用法。
      

  8.   

    import java.io.*;
    import javax.swing.filechooser.FileFilter;   
    import javax.swing.*;                          
    public class ch8_10 extends JFrame                   
    {  
     chooseFile Jfc = new chooseFile();             //建立选择档案对话方块盒 Jfc
       JFrame   frame1 = new JFrame ();
     public static void main(String args[])
     {     new ch8_10();
     }
     public ch8_10()      
     {
      a();
          
     }
     public void a()
      {
        frame1.setTitle("档案选择对话方块");
       frame1.setSize(550,350);    
      frame1.setVisible(true);
       Filter filter = new Filter();                 //建立文件显示对象 filter             
      Jfc.addChoosableFileFilter(filter);           //新增显示文件类型为 filter
      frame1.getContentPane().add(Jfc);  
    }
     public class chooseFile extends JFileChooser   //chooseFile 继承 JFileChooser
     {
      File select;
      String filename;
      public chooseFile()                           //构造函数
      {
       super("c:/");                                //调用父类别中的构造函数
      }
      public void approveSelection()                //使用者按下核选按钮
      {
       select = Jfc.getSelectedFile();              //取得选择的文件
       filename = Jfc.getName(select) ;             //取得文件名
       JOptionPane.showMessageDialog(getContentPane(),"你选择了文件 " + filename);
       /* 显示信息对话框 */
      }
      public void cancelSelection()                 //使用者按下取消按钮
      {
       JOptionPane.showMessageDialog(getContentPane(),"取消此次的选择!");
       /* 显示信息对话框 */
       Jfc.setSelectedFile(null);                   //重设被选取的文件为 null
      }
     }
     public class Filter extends FileFilter         //Filter 继承 FileFilter
     {
      public boolean accept(File file)
      {
       return(file.getName().endsWith(".txt") || file.isDirectory());
       /* 返回要显示的文件类型 */
      }
      public String getDescription()
      {
       return("TXT Files(*.txt)");                  //返回显示文件类型的描述
      }
     }
    }
     
      

  9.   

    public void convert_(String filename ,String dir, File file)
    {
    try
    {
    if( dir == null )
      dir  = System.getProperty("user.dir");
        
    FileFilter fileFilter = new FileFilter () {
      public boolean accept(File aFile)
      {
     return ( aFile.isDirectory() || aFile.getName().endsWith(".svg") );
      }   public String getDescription()
      {
    return "SVG Files (*" + ".svg" + ")";
      }
    };
    //----------------------------------------
    while(true) 
    {

    JFileChooser fileChooser = new JFileChooser(dir);
    fileChooser.addChoosableFileFilter(fileFilter);
    fileChooser.setFileFilter(fileFilter);
    int option = fileChooser.showSaveDialog(null);
    if(option == JFileChooser.APPROVE_OPTION) 
    {
    file = fileChooser.getSelectedFile();
    if( file.getName().endsWith(".svg") ) {
      dir = fileChooser.getCurrentDirectory().getAbsolutePath();
      if( file.exists() ) {
    int i = JOptionPane.showConfirmDialog(null,"File already exists. Overwrite?",
      "Warning",
      JOptionPane.YES_NO_OPTION,
      JOptionPane.WARNING_MESSAGE);
    if( i != JOptionPane.YES_OPTION )
      continue;
      }
      filename = file.getAbsolutePath();
      break;
    } else {
      JOptionPane.showMessageDialog(null,
    "The selected file must be of type .svg",
    "Invalid file type",
    JOptionPane.INFORMATION_MESSAGE);
      continue;
    }
      } else {
      break;
     }
    }
                           System.out.println(filename } catch (Exception e)
    {
    System.out.println(e.toString());
    }
    }
      

  10.   

    //FileFilter测试import java.io.*;class FileFilterTest implements FilenameFilter{
    String extent;
    FileFilterTest(String extent){
    this.extent = extent;
    }
    public boolean accept(File dir,String name){
    return name.endsWith("." + extent);
    }
    public static void main(String[] args){ File dir = new File("/XXX");
    FileFilterTest fft = new FileFilterTest("htm");
    System.out.println("list html files in  directory " +dir);

    String files[] = dir.list(fft);
    //System.out.println(files.length);
    for (int i=0;i<files.length;i++ )
    {
    File f = new File(files[i]);
    if(f.isFile())
    System.out.println("file:" + f);
    else
    System.out.println("sub director " + f);
    }
    }
    }
      

  11.   

    俺的文档,里面说得很清楚了
    http://www.csdn.net/develop/read_article.asp?id=17710