Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
String from BufferedReader is not equal to string literal

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:

enter image description here

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:

enter image description here

Key in map:

enter image description here

Does anyone know how I can fix this and make the value from file equal the literal?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda