Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java find start of file name and extension

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 =================");
            }
        }
    }
like image 749
James Avatar asked Dec 29 '22 02:12

James


2 Answers

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.");

like image 143
Vladimir Ivanov Avatar answered Jan 04 '23 09:01

Vladimir Ivanov


You can use FileNameFilter

public void listFiles() {

        File f = new File("C:/");
        String[] allFiles = f.list(new MyFilter ());
        for (String filez:allFiles ) {
            System.out.println(filez);
        }
    }
    class MyFilter implements FilenameFilter {


        @Override
        public boolean accept(final File dir, final String name) {
            return name.startsWith("LAYER.EXE.pf");
        }
    }
like image 42
Luciano Fiandesio Avatar answered Jan 04 '23 08:01

Luciano Fiandesio