How to make FileFilter in java?

后端 未结 9 2143
清歌不尽
清歌不尽 2020-12-05 02:07

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

i wrote something like this but it has error :(

 private void jMenuItem1ActionPerformed(java.awt.even         


        
9条回答
  •  隐瞒了意图╮
    2020-12-05 02:45

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

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

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

提交回复
热议问题