如何在java中创建FileFilter?

时间:2011-04-09 08:54:25

标签: java filefilter

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

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

 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();
        }

10 个答案:

答案 0 :(得分:47)

尝试这样的事情......

String yourPath = "insert here your path..";
File directory = new File(yourPath);
String[] myFiles = directory.list(new FilenameFilter() {
    public boolean accept(File directory, String fileName) {
        return fileName.endsWith(".txt");
    }
});

答案 1 :(得分:24)

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

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

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,它具有带文件名作为参数的accept方法,因此您不需要手动获取它。

答案 2 :(得分:8)

从JDK8开始,单词就像

一样简单
final String extension = ".java";
final File currentDir = new File(YOUR_DIRECTORY_PATH);
File[] files = currentDir.listFiles((File pathname) -> pathname.getName().endsWith(extension));

答案 3 :(得分:5)

从Java7开始,您只需使用FileNameExtensionFilter(String description, String... extensions)

即可

示例的简单JFileChooser类似于:

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt"));

我知道很久以前就回答了这个问题,但这实际上是最简单的解决方案。

答案 4 :(得分:3)

这是我创建的一个小实用程序类:

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Convenience utility to create a FilenameFilter, based on a list of extensions
 */
public class FileExtensionFilter implements FilenameFilter {
    private Set<String> exts = new HashSet<String>();

    /**
     * @param extensions
     *            a list of allowed extensions, without the dot, e.g.
     *            <code>"xml","html","rss"</code>
     */
    public FileExtensionFilter(String... extensions) {
        for (String ext : extensions) {
            exts.add("." + ext.toLowerCase().trim());
        }
    }

    public boolean accept(File dir, String name) {
        final Iterator<String> extList = exts.iterator();
        while (extList.hasNext()) {
            if (name.toLowerCase().endsWith(extList.next())) {
                return true;
            }
        }
        return false;
    }
}

用法:

       String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));

答案 5 :(得分:0)

你错了:

int retval = chooser.showOpenDialog(null); 
public boolean accept(File directory, String fileName) {`
return fileName.endsWith(".txt");`
}

首先显示文件选择器对话框,然后应用过滤器!这不行。首先应用过滤器,然后显示对话框:

public boolean accept(File directory, String fileName) {
        return fileName.endsWith(".txt");
}
int retval = chooser.showOpenDialog(null);

答案 6 :(得分:0)

另一个简单的例子:

public static void listFilesInDirectory(String pathString) {
  // A local class (a class defined inside a block, here a method).
  class MyFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      return !file.isHidden() && file.getName().endsWith(".txt");
    }
  }

  File directory = new File(pathString);
  File[] files = directory.listFiles(new MyFilter());

  for (File fileLoop : files) {
    System.out.println(fileLoop.getName());
  }
}

// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");

// Output
Cool.txt
RedditKinsey.txt
...

答案 7 :(得分:0)

File f = null;
File[] paths;

try {

    f = new File(dir);

    // filefilter
    FilenameFilter fileNameFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {

            if (name.lastIndexOf('.') > 0) {

                int lastIndex = name.lastIndexOf('.');
                String str = name.substring(lastIndex);

                if (str.equals("." + selectlogtype)) {
                    return true;
                }
            }
            return false;
        }
    };

    paths = f.listFiles(fileNameFilter);

    for (int i = 0; i < paths.length; i++) {
        try {

            FileWriter fileWriter = new FileWriter("C:/Users/maya02/workspace/ftp_log/filefilterlogtxt");
            PrintWriter bWriter = new PrintWriter(fileWriter);

            for (File writerpath1 : paths) {
                bWriter.println(writerpath1);
            }

            bWriter.close();
        } 
        catch (IOException e) { System.out.println("HATA!!"); }
    }
    System.out.println("path dosyaya aktarıldı!.");
} 
catch (Exception e) { }

答案 8 :(得分:0)

...从以下位置使用Apache的FileFilters怎么样? org.apache.commons.io

就像:

 import org.apache.commons.io.filefilter.FileFileFilter;
 import org.apache.commons.io.filefilter.WildcardFileFilter;

 ...

 File dir = new File(".");

 String[] filters = { "*.txt"};
 IOFileFilter wildCardFilter = new WildcardFileFilter(filters, IOCase.INSENSITIVE);

 String[] files = dir.list( wildCardFilter );
 for ( int i = 0; i < files.length; i++ ) {
     System.out.println(files[i]);
 }

答案 9 :(得分:0)

FileFilter filtro=new ExtensionFileFilter("Excel", ".csv");