如何在java中创建FileFilter? [英] How to make FileFilter in java?

查看:291
本文介绍了如何在java中创建FileFilter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在标题中如何过滤到.txt文件?

like in title how to make filter to .txt files?

我写了这样的东西,但它有错误:(

i wrote something like this but it has error :(

 private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        JFileChooser chooser = new JFileChooser();
        int retval = chooser.showOpenDialog(null);

        String yourpath = "E:\\Programy Java\\Projekt_SR1\\src\\project_sr1";
        File directory = new File(yourpath);
        String[] myFiles;
        FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File directory, String fileName) {
            return fileName.endsWith(".txt");
        }
        };
        myFiles = directory.list(filter);


        if(retval == JFileChooser.APPROVE_OPTION)
        {
            File myFile = chooser.getSelectedFile();
        }


推荐答案

这里你会发现一些有用的例子。 也是JFileChooser中使用的FileFilter的一个很好的例子。

Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

基础是,你需要覆盖 FileFilter 类,并在其accpet方法中编写自定义代码。上例中的accept方法是根据文件类型进行过滤:

The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() 
                  - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
}

或者更简单易用的是 FileNameFilter ,其接受方法使用filename作为参数,因此您无需获取它手动。

Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.

这篇关于如何在java中创建FileFilter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆