Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - String.contains() behaves oddly

this snippet of code works fine on my development machine (Windows 7 installed on VirtualBox jre 8 using Netbeans IDE), but on another machine (Windows 7 jre 8) always returns true. It should only find files with a name like "town_house.html" instead it always returns true for every file in the folder.Running the jar file from prompt I don't get any exceptions. Maybe it's just a trivial error I usually program in C/C++ ... any idea?

for(File f : files)
        {
            if(f.toString().contains("_") && 
               f.toString().contains(".html")){
                System.out.print("Processing file: " + f.getName()+ "\n");
                String[] fileSplit = f.getName().split("_");
                towns.add(fileSplit[0]);

            }
        }

Thanks in advance

like image 975
abbadon Avatar asked Aug 27 '26 07:08

abbadon


1 Answers

You are checking toString() instead of getName() - maybe the directory path contains an underscore.

Try this instead (note also simplified test):

for(File f : files) {
    if (f.getName().matches(".*_.*\\.html")) {
        System.out.print("Processing file: " + f.getName()+ "\n");
        String[] fileSplit = f.getName().split("_");
        towns.add(fileSplit[0]);
    }
}
like image 77
Bohemian Avatar answered Aug 29 '26 21:08

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!