Ruben de groot
Ruben de groot

Reputation: 15

If statement does equalsIgnoreCase while not prefered

If I use this code:

if(new File(inputNickname + ".acc").exists() == false) {
    System.out.println("[Login] This account does not exists!");
    exists = false;
}

and I would make a text file called example.acc, it will say true if inputNickname = "EXAMPLE" or "ExAmPle", etc. But I only want that exists = true, when inputNickname is "example" and not "EXAMPLE" or "ExAmPlE" etc.

Upvotes: 0

Views: 449

Answers (3)

BackSlash
BackSlash

Reputation: 22243

If this happens, likely you are on windows. Windows is not case-sensitive on file names, so you can do really nothing here. In windows "Example" and "eXAmple" is the exact same thing. That's why your if returns true.

One thing you can do is to explicitly match the name, without using the File.exists method, as follows:

final String account = "ExAmple.acc";
String accountsDirectory = ".";
File[] accountFiles = new File(accountsDirectory).listFiles(
    new FilenameFilter() {
        public boolean accept(File dir, String name) {
            // accept only files having the exact same name as "account"
            // this IS case sensitive.
            return name.equals(account);
        }
    }
);

if(accountFiles.length > 0) {
    // there is at least one file with the specified name, handle this
} else {
    // no accounts found!
}

But, again, on Windows this completely doesn't make sense, as you cannot have multiple files with the same name and different upper/lower letters, as it is case-insensitive. This doesn't make sense also on unix-based systems, as they are case sensitive on file names, so you wouldn't need to worry about the File.exists method giving unexpected results.

My suggestion: Use a database for your accounts.

Upvotes: 2

Bethany Louise
Bethany Louise

Reputation: 646

Many filesystems (including those used by Windows) are not case-sensitive. If your computer uses a filesystem that is not case-sensitive, then your code will return true if the given file exists regardless of capitalization in the filename. If you want to make your program case-sensitive anyway, you could do this (if all filenames you'll search for will be all-lowercase):

if (!inputNickname.toLowerCase().equals(inputNickname) || !(new File(inputNickname + ".acc").exists())) {
    System.out.println("[Login] This account does not exist!");
    exists = false;
}

Upvotes: 0

Ashwin Baweja
Ashwin Baweja

Reputation: 29

You can use the toLowerCase function for a String as such:

if(new File(inputNickname.toLowerCase() + ".acc").exists() == false) {
    System.out.println("[Login] This account does not exists!");
    exists = false;
}

For more info: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toLowerCase()

Upvotes: 0

Related Questions