Java find start of file name and extension

James picture James · Jan 31, 2011 · Viewed 8.1k times · Source

HI, I have almost solved this but have now got stuck! What I need to do is look in a folder say..

String path = C://;

I then need a loop to see how many files are in that folder say 10. I need to look for files that start like

LAYER.EXE-******.pf

***** can change depending of other things but thats not important what is, is making sure when it finds a file that starts LAYER.EXE- it flags it up. Below is what I have been working on, I would vert much like you're help and thank you in advance! :)

    String path = "C://";
    String files;
    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();
                System.out.println(files);
                if (files == "LAYER.EXE.pf"){
                    System.out.println("found =================");
            }
        }
    }

Answer

Vladimir Ivanov picture Vladimir Ivanov · Jan 31, 2011
files == "LAYER.EXE.pf"

change to

"LAYER.EXE.pf".equals(files)

What you do is a reference comparison, and you need the equality. Read more here.

Telling more, this will give you only the files which name is equal to "LAYER.EXE.pf".

Try files.startsWith("LAYER.");