There are a lot of posts from people using == instead of equals but this isn't one of them.
I'm reading a list of codes from a CSV file making sure they are equal to a string literal.
Example row from CSV:
After reading each code, I trim and call toUpper() before placing them inside a map.
private final Map<String, Code> codeMap = new HashMap<>();
private void loadFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("src/main/resources/codes.csv"));
String line = null;
while ((line = reader.readLine()) != null) {
String[] details = line.split(",");
codeMap.put(details[0].trim().toUpperCase(), new Code(details[0].trim(), details[1].trim(), details[2].trim()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I also have a method for retrieving a code based on the string passed in:
public Tool getCodeByString(String code){
return codeMap.get(code.toUpperCase());
}
After the map is populated, I call getCodeByString using "CHNS" and null is returned. I looked in the map and see the key "CHNS" but null is being returned. I can immediately tell the byte arrays are different.
String literal:
Key in map:
Does anyone know how I can fix this and make the value from file equal the literal?
It seems you are reading a UTF-8 file, with a redundant BOM character \uFEFF (bytes -2, -1).
So you should discard the BOM, and actually read the file as UTF-8 (for any special characters).
However as FileReader reads the file in default platform encoding, use an other reading.
Also you are reading from a resource file. This will be packed in the application (jar?), so you should not read it as disk File.
Files.lines uses by default UTF-8.
private void loadFile() {
Path path = Paths.get(getClass().getResource("/codes.csv").toURI());
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(line -> {
String[] details = line.split("\\s*,\\s*", 3);
String key = details[0].replace("\uFEFF", "");
// Replace of BOM would only be needed at the file begin.
codeMap.put(key.toUpperCase(), new Code(key, details[1], details[2]));
});
} catch (IOException e) {
e.printStackTrace();
} // Automatic close of lines.
}
The regex of split strips whitespace before and after the comma. Also limited the split to 3 values, so the last field may contain commas as text.