Starting a project, and this irriating me. I think the code is okay, but I don’t understand how to either return a record or parse the line.
I have a CSV file, which displays like this in Libra.
USER PASSWORD
Chris Password
Michelle Password
John Password
I am getting the user to enter their user and password, and then trying to compare those against the CSV to make sure that 1) the username exists and 2) if it does, that the password is correct. To be honest, part 2 isn’t essential as it’s not part of the spec but I want to do it, and I suspect it would be the same problem as what I am having anyway. As I said, I think the code is okay, but I’m not sure what format the variable thisLine will have and is my else statement moving the BufferedReader onto the next line correctly?
Can I use thisLine.trim() to cut USER PASSWORD does to just USER?
static void readFromCsvFile(String sFileName, User user) throws FileNotFoundException
{
String thisLine;
try
{
BufferedReader reader = new BufferedReader(new FileReader(sFileName));
thisLine = reader.readLine();
System.out.print(thisLine);
while((thisLine = reader.readLine()) != null)
{
if (user.displayUserName() == thisLine)
{
System.out.print("\nUser <-" + user.displayUserName() + " -> exists!");
reader.close();
}
else
{
thisLine = reader.readLine();
}
}
}
catch(IOException e)
{
System.out.print("\nUser does not exist\n");
e.printStackTrace();
}
Several remarks here:
1)
thisLine.trim()will just remove the trailing blanks at the beginning and ending of thethisLinecontents. It is okay to do so, specially if you are going to compare two strings, but it won’t split the username and password from the variable.2) To split the two different values you should use
thisLine.split(" ")(I’m assuming that your CSV file uses blanks to separate the different fields).3) Another mistake is to compare the strings using
==rather thanequals, which is the correct way of doing it.4) Since you are reading a new line in the
whilecondition you don’t need the internalreader.readLine()5) Finally, never close the stream (or reader) inside the loop!! Do it on a
try/catch/finallyblock.So, with those corrections your code will look like: