如果我执行这段代码:
public static void main(String[] args) {
load_Players("Netherlands");
}
private static void load_Players(String team_Name) {
String path = "team_Netherlands.txt"; // works
String path2 = "team_" + team_Name + ".txt"; // doesn't work?
System.out.println("are " + path + " and " + path2 + " the same? " + path.equals(path2));
}
一切都按预期进行,所以...出了什么问题?
正如您在日志中看到的,第一个荷兰不是蓝色的,这意味着解析器发现了不同的东西。
可疑啊?
CHECKS:
当我将这部分代码粘贴到我的 eclipse 中时:
team_Netherlands.txt and team_Netherlands.txt
保存时出现此错误:
如果我选择选项选择第一个字符,它会选择:
System.out.println("team_Netherlands.txt".equals("team_Netherlands.txt"));
↑ this one!!!
因此,您传递了错误的编码,您可以使用以下代码片段进行检查:
public static void main(String[] args) {
String rightString = "_Netherlands.txt";
String wrongString = "_Netherlands.txt";
System.out.println("WRONG HASH");
System.out.println(rightString.hashCode());
System.out.println("\nRIGHT HASH");
System.out.println(wrongString.hashCode());
System.out.println("\nRIGHT");
printChars(rightString);
System.out.println("\n\nWRONG");
printChars(wrongString);
}
private static void printChars(String s) {
for (Character c : s.toCharArray()) {
System.out.print((int) c + " ");
}
}
OUTPUT:
WRONG HASH
1109617587
RIGHT HASH
-428164238
RIGHT
95 78 101 116 104 101 114 108 97 110 100 115 46 116 120 116
WRONG
95 65279 78 101 116 104 101 114 108 97 110 100 115 46 116 120 116
// ↑ here!!
解决方案:(source http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html)
测试一下!:
public static void main(String[] args) throws Exception {
String rightString = "Netherlands.txt";
String wrongString = "Netherlands.txt";
System.out.println("\nCOMPARE");
System.out.println(rightString.equals(wrongString));
System.out.println("\nCLEAN COMPARE");
System.out.println(clean(rightString).equals(clean(wrongString)));
System.out.println("\nRIGHT");
printChars(clean(rightString));
System.out.println("\n\nWRONG");
printChars(clean(wrongString));
}
private static String clean(String s) throws Exception {
InputStream is = new ByteArrayInputStream(s.getBytes());
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
// BOM marker will only appear on the very beginning
br.mark(4);
if ('\ufeff' != br.read())
br.reset(); // not the BOM marker
return br.readLine();
}
}
private static void printChars(String s) {
for (Character c : s.toCharArray()) {
System.out.print((int) c + " ");
}
}
OUTPUT:
COMPARE
false
CLEAN COMPARE
true
RIGHT
78 101 116 104 101 114 108 97 110 100 115 46 116 120 116
WRONG
78 101 116 104 101 114 108 97 110 100 115 46 116 120 116