Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make FileFilter in Java?

How to make a filter for .txt files?

I wrote something like this but it has an 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();         } 
like image 795
Harry89pl Avatar asked Apr 09 '11 08:04

Harry89pl


People also ask

How to use FileFilter in Java?

The java. io. File. listFiles(FileFilter filter) returns an array of abstract pathnames indicating the files and directories in the directory indicated by this abstract pathname that satisfy the specified filter.

What is FilenameFilter in Java?

Java FileFilter is a filter for File objects denoting the files and subdirectories in a given directory. It is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

What support is provided by file class for file management?

The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories. It is an abstract representation of files and directory pathnames.


1 Answers

Try something like this...

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");     } }); 
like image 127
Fseee Avatar answered Oct 24 '22 15:10

Fseee