How to fix wrong output of content.Equals?

Viewed 125

I am trying to let Java read all files in a directory and compare the filenames to a list of strings, if a filename is the same as a string in the list it should output the filename + "hit". Now I get a hit on only one file.

the folder hit contains: foto5.jpeg yH1laMN0s7g.jpeg RdrzTHAvcQg.jpeg

The list lijst.txt contains: foto5.jpeg yH1laMN0s7g.jpeg RdrzTHAvcQg.jpeg

So I should get: foto5 Hit! RdrzTHAvcQg Hit! yH1laMN0s7g Hit!

But what I get now is: foto5 * RdrzTHAvcQg Hit! yH1laMN0s7g *

I have tried to play with the coding, which is now UTF-8. But I don't think that's the problem.

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    String hit = ""; // empty string

    File files = new File("C:\\Users\\bram\\Pictures\\hit");
    File[] sourceFiles = files.listFiles();  // the files in the map hit java reads

    List<String> lines = new ArrayList<String>();
    try {
        lines = FileUtils.readLines(new File("C:\\lijst.txt"), "utf-8");
    } catch (IOException e2) {
    }  // java reads strings in the list

    for (File x: sourceFiles) {  // java iterates through all the files in the folder hits. 

        String names = x.getName().replaceAll("\\.[^.]*$", "").toString(); 
        // java gets the filenames and converts them to strings without the extension

        for (String a : lines) // for all strings in the list:
        {   
            //System.out.println(a);
            if(names.contentEquals(a))  // if the name is equel to one of the strings in the list it generates a hit
            {
                hit = "Hit!";
            }else {
                hit = "*";              // no hit is * 
            }
        }

    System.out.println(x.getName().replaceAll("\\.[^.]*$", "").toString() +"         "+ hit); // print the results

    }

  }

  }
2 Answers

You are overcomplicating things. Why do you remove the file extensions although your txt file contains the full names of your images files? why a nested for loop? Dosen't something like below suffice?

for (File x : sourceFiles) {            
        if(lines.contains(x.getName())){
            System.out.println(x.getName()+"\t Hit!");
        }
        else{
            System.out.println(x.getName()+"\t *");
        }
    }

Allright, sorry guys.. It has been a long day. The list with the strings did not contain any extensions. Wrong information from my side, sorry.

I got it working now, with just a simple break in the for-loop. Thanks for the responses!

for (String a : lines) // for all strings in the list:
        {   
            //System.out.println(a);
            if(names.contentEquals(a))  
            {
                hit = "Hit!";
                break;
            }else {
                hit = "*";              // no hit is * 
            }

        }
Related