0

I searched now for a few hours to find a solution to my beginner Java problem but I cannot seem to do it.

I am trying to check a directory for filenames that I would like to test against a list. If the Filename exists I would like to do something. The problem is that the filename is never found, even when the file clearly exists. I am using java.io.File to get the directory filenames.

My problem is that the file is called "test1_1.txt" and the method returns "test1_1.txt" in a println statement but Java tells me they are not the same. Hence I never can actually make Java tell me which files do already exist.

System.out.println(listOfFiles[i].getName()); is showing me "test1_1.txt"

but:

public static void main(String[] args){

        File folder = new File(C:\\Users\\M\\Desktop\\coding\\);
        File[] listOfFiles = folder.listFiles();

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

        if (listOfFiles[i].getName() == "test1_1.txt"){
            System.out.println("found");
        }
    }}

never says "found"

Im grateful for any help.

Decar
  • 5
  • 1
  • 3
    Use String.equals to comapre strings instead of == – Juned Ahsan Nov 02 '15 at 23:26
  • you can also use String.equalsIgnoreCase() method to make you comparison case insensitive – BustedSanta Nov 02 '15 at 23:28
  • Strings in Java are immutable and the == operator is not overloaded for Strings. As such, you are comparing object references which will be different. Use "test1_1.txt".equals(listOfFiles[i].getName()) instead. – Michael Krause Nov 02 '15 at 23:28
  • What's wrong with `File#exists`? – MadProgrammer Nov 02 '15 at 23:46
  • thank you everyone ! It works perfectly now and also thank you for linking it to the other thread where it was explained with a lot of detail why it made no sense what I did. I did not use File#exists because I don't know how at the moment, but I will check that out. Thanks again, I really appreciated the help. – Decar Nov 03 '15 at 06:08

0 Answers0