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(); }
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.
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.
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.
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"); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With