So my issue is I'm attempting to read and write from a CSV file but I'm having an issue with appending to a new line and then reading without getting the following error:
Now I think I know why I'm getting the error but I can find a way to fix it. I'm writing to the file with the following code:
public void writeToFile(AbstractAccount account)
{
StringBuilder sb = new StringBuilder();
sb.append(account.getFirstname() + ",");
sb.append(account.getLastname() + ",");
sb.append(account.getID() + ",");
sb.append(account.getPhonenum() + ",");
sb.append(account.getUsername() + ",");
sb.append(account.getPassword() + ",");
sb.append(account.getAccounttype());
FileWriter fw = null;
try
{
fw = new FileWriter("login.csv", true);
fw.append(System.lineSeparator() + sb.toString());
fw.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
The issue is that the inside of the CSV file looks like this:
John,Doe,A1,0123456789,johnd,password1,Admin
Jane,Doe,A2,1234567890,janed,password2,CourseCoordinator
John,Smith,A3,2345678901,johns,password3,Approver
Jane,Smith,A4,356789012,johns,password4,CasualStaff
Test, Test, Test, Test, test, test, Admin
But when I copy it somewhere like into the stack overflow text editor I can see that the actual format is this:
John,Doe,A1,0123456789,johnd,password1,Admin
Jane,Doe,A2,1234567890,janed,password2,CourseCoordinator
John,Smith,A3,2345678901,johns,password3,Approver
Jane,Smith,A4,356789012,johns,password4,CasualStaff
Test, Test, Test, Test, test, test, Admin
So when I read from the file using this code:
public ArrayList<AbstractAccount> readFromFile(String filename)
{
BufferedReader br = null;
String line = "";
try
{
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null)
{
// use comma as separator
String[] attributes = line.split(",");
accounts.add(CreateAccount(attributes));
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return accounts;
}
I get that error I mentioned before. I've tried a few ways of writing to a new line but I can't find one that doesn't give me that blank line. Anyone got any ideas?
EDIT: Code for Create Account
public AbstractAccount CreateAccount(String[] data)
{
String firstname = data[0];
String lastname = data[1];
String id = data[2];
String phonenum = data[3];
String username = data[4];
String password = data[5];
String accounttype = data[6];
if (accounttype.equals("Admin"))
return new AdminModel(firstname, lastname, id, phonenum, username, password);
else if (accounttype.equals("CourseCoordinator"))
return new CourseCoordinatorModel(firstname, lastname, id, phonenum, username, password);
else if (accounttype.equals("Approver"))
return new ApproverModel(firstname, lastname, id, phonenum, username, password);
else if (accounttype.equals("CasualStaff"))
return new CasualStaffModel(firstname, lastname, id, phonenum, username, password);
else
return null;
}

CreateAccount. The exception happens there