Filenamefilter I need you to let me know when I can not find anything

1

I have the following program:

public class filtrado {

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

try{
        File f = new File("."); // current directory
        FilenameFilter textFilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                String lowercaseName = name.toLowerCase();
                return lowercaseName.startsWith("g");                   
            }
        };
            File[] files = f.listFiles(textFilter);
        for (File file : files) {                 
                    if (file.isDirectory()) {
                System.out.print("directory:");
            } else {
                System.out.print("     file:");
            }
            System.out.println(file.getCanonicalPath());
                }

                }catch (Exception e) { 
                }

    }

}

Basically the operation is as follows: I look in my directory for any file that starts with "g". And classifies it into a directory or file.

But I need something else that I do not know how to do. I need when I can not find any file that lets me know, for example: There is no File / Directory that starts with G.

How do I do it?

    
asked by Montse Mkd 24.02.2017 в 17:48
source

2 answers

1

Try as follows, try it and it works as you request.

try {
        File f = new File("."); // current directory

        FilenameFilter textFilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                String lowercaseName = name.toLowerCase();
                return lowercaseName.startsWith("g");
            }
        };

        File[] files = f.listFiles(textFilter);
        if (files.length > 0) {
            for (File file : files) {
                if (file.isDirectory()) {
                    System.out.print("directory:");
                } else {
                    System.out.print("     file:");
                }
                System.out.println(file.getCanonicalPath());
            }
        } else{
            System.out.println("No existe ningun Fichero/Directorio que empiece con G");
        }
    } catch (Exception e) {
    }
    
answered by 25.02.2017 / 22:19
source
0

You can count how many times your loop finds Files / Directories that match the letter G, otherwise you put the message you want

    
answered by 24.02.2017 в 18:02