I'm trying to read a string from a .csv
file (separeted by ;
) and then compare the first column to the login
string. Here is my code:
FileReader file = new FileReader("MyCSV.csv");
BufferedReader entry = new BufferedReader(file);
String row;
row = entry.readLine();
do {
String[] value = row.split(";");
if (login.equals(value[0])) { // login is passed as an argument to his function
// do something
}
row = entry.readLine();
} while (row != null);
I can read the entire file, but I'm not being able to search for the first user register. The login
comparison always returns false
to the first one. I tried:
if (value[0].equals(login))
if (value[0] == login)
An example in console:
// I've put this inside `do while`
System.out.println(value[0] + " and " + login + " = " + login.equals(value[0]));
And the result is:
leonidas and leonidas = false
rafatcb and leonidas = false
davinci and leonidas = false
login and leonidas = false
If I compare to "rafatcb"
:
leonidas and rafatcb = false
rafatcb and rafatcb = true // true, as expected
I also tried the following code, but it still returns false
for "leonidas"
:
value[0].trim().equals(String.valueOf(login.trim()));
As suggested in the comments, I printed using .toCharArray()
:
System.out.println(Arrays.toString(value[0].toCharArray()));
System.out.println(Arrays.toString(login.toCharArray()));
And the result was:
[, l, e, o, n, i, d, a, s]
[l, e, o, n, i, d, a, s]
Since you are reading from a file there may be non printable characters in your variable value[0]
. You can replace them as below
value[0].replaceAll("\0", "").equals(login)
and it should work fine.