How to search files by extension and name that is entered by the user?

David Krizmanić :

Where should I include a statement in my code so that it searches by both the extension which is alredy encoded, and the name of the file which the user enters?


private void btnSearchMouseClicked(java.awt.event.MouseEvent evt) {                                       
        File folder = new File(txtLocation.getText());
        String name = new String (txtName.getText());

        if(folder.isDirectory() == true){
           String [] files  = folder.list();
           String fileNames = "";

           for(int i=0; i<files.length; i++){
               int index = files[i].indexOf(".");
               String extension = files[i].substring(index);
               if(extension.equals(".jpg")==true ){

               fileNames += "\n" + files[i];
               }


           }
           txtListOfFiles.setText("Files found:" + fileNames);
        }
JavaSheriff :
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Scanner;

public class DirectoryContents {

    public static void main(String[] args) throws IOException {

        File f = new File("c:\\temp\\"); // current directory
        Scanner myObj = new Scanner(System.in);  // Create a Scanner object
        System.out.println("Enter file ext:");

        final String fileExt = myObj.nextLine();  // Read user input
        System.out.println("file ext is: " + fileExt);   
        myObj.close();

        File[] files = f.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith("."  +fileExt);
            }
        });
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.print("directory:");
            } else {
                System.out.print("     file:");
            }
            System.out.println(file.getCanonicalPath());
        }
    }
}

source

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153601&siteId=1