如果我使用此代码:
if(new File(inputNickname + ".acc").exists() == false) {
System.out.println("[Login] This account does not exists!");
exists = false;
}
我会创建一个名为example.acc
的文本文件,
如果true
或inputNickname = "EXAMPLE"
等,它会说"ExAmPle"
。
但我只想exists = true
,inputNickname
为"example"
而非"EXAMPLE"
或"ExAmPlE"
等。
答案 0 :(得分:2)
如果发生这种情况,很可能是在Windows上。 Windows在文件名上不区分大小写,因此您可以在此处执行任何操作。在Windows中“示例”和“eXAmple”完全相同。这就是你的if返回true的原因。
您可以做的一件事是明确匹配名称,而不使用File.exists
方法,如下所示:
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!
}
但是,再一次,在Windows上这完全没有意义,因为它不能有多个具有相同名称和不同大写/小写字母的文件,因为它不区分大小写。
这在基于unix的系统上也没有意义,因为它们对文件名区分大小写,因此您不必担心File.exists
方法会产生意外结果。
我的建议:为您的帐户使用数据库。
答案 1 :(得分:0)
您可以将toLowerCase
函数用于String:
if(new File(inputNickname.toLowerCase() + ".acc").exists() == false) {
System.out.println("[Login] This account does not exists!");
exists = false;
}
了解更多信息:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toLowerCase()
答案 2 :(得分:0)
许多文件系统(包括Windows使用的文件系统)不区分大小写。如果您的计算机使用的文件系统不区分大小写,那么如果给定的文件存在,则无论文件名中的大小写如何,您的代码都将返回true
。如果你想让你的程序区分大小写,你可以这样做(如果你要搜索的所有文件名都是全小写的):
if (!inputNickname.toLowerCase().equals(inputNickname) || !(new File(inputNickname + ".acc").exists())) {
System.out.println("[Login] This account does not exist!");
exists = false;
}