Search for a word within the Java Files variable

2

I have the following code in java I would need to search the result returned the name of a specific file, the problem is that this way I search by extension and not by the name and I can not think of how to perform a search by name . I hope you can help me.

public static void main(String[] args) 
{

    // Aquí la carpeta que queremos explorar
    String path = "C://Users//Federico//Downloads"; 

    String files = null;

    File folder = new File(path);
    File[] listOfFiles = folder.listFiles(); 

    for (int i = 0; i < listOfFiles.length; i++) {

        if (listOfFiles[i].isFile()) {
            files = listOfFiles[i].getName();
            if (files.endsWith(".seq") || files.endsWith(".SEQ")){
                System.out.println(files);
            }
        }

        }String s = files;
        s.charAt(60);
    for (int x = 0; x < s.length(); x++) {
        System.out.println(s);
    }
 }
}
    
asked by federico vazquez 09.03.2018 в 19:26
source

2 answers

1

In principle, what you should do is use the method of the class String contains , which allows to search in a chain the occurrence of another, and therefore should be worth replacing the line:

if (files.endsWith(".seq") || files.endsWith(".SEQ")){

For something like the following:

 if (files.toLowerCase().contains("seq")){

By the way, I've passed the string to lowercase before, so you do not have to look for it in two different ways.

You can check the String API in: link

    
answered by 09.03.2018 в 19:32
1

You are looking for an extension because the method searches if the string ends with .seq

  

endsWith () : Test if this string ends with the suffix   specified.

If you want to search for the text inside the file name you can use the method:

  

contains () : Returns true if and only if this string contains the specified sequence of char values.

Therefore instead of:

 if (files.endsWith(".seq") || files.endsWith(".SEQ")){
   System.out.println(files);
 }

You can change to:

String textoBuscar = ".seq"; //Define aquí el texto a buscar.
if (files.contains(textoBuscar)){
   System.out.println(files);
}

If you want to search for text regardless of uppercase or lowercase you can also add the method toLowerCase ()

String textoBuscar = ".SeQ"; //Define aquí el texto a buscar.
if (files.toLowerCase().contains(textoBuscar)){
   System.out.println(files);
}
    
answered by 09.03.2018 в 23:27