I am making an application to act as a simple classroom library with books and users. There are teacher and student user types. I have no database and understand that the program can't run at all times, so the changed/added information while it is running should be saved when the program ends. The problem I am facing is that it is writing the information to the csv file in a manner I don't understand.
Main.java File
public static void main(String[] args) throws IOException {
Library library = new Library();
User teacher = new Teacher("admin", "password");
library.addUser(teacher);
library.loadUsers("/path/to/users.csv");
library.addUser(new Student("student3"));
//library.loadBooks("/path/to/books.csv");
//library.loginTeacher("admin", "password");
//library.addBook(new Book("hhg", "hhg", "hjhjf", 40));
//library.printBooks();
//library.saveBooks("/path/to/books.csv");
library.saveUsers("/path/to/users.csv");
}
users.csv
student1,
student2,
Library.java
public void loadUsers(String userDir) {
File myFile1 = new File(userDir);
Scanner scanner = null;
try {
scanner = new Scanner(myFile1);
scanner.useDelimiter(",");
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
ArrayList<String[]> data = new ArrayList<>();
while (scanner.hasNext()) {
String line = scanner.next();
String[] r = line.split(",");
data.add(r);
}
for(int i = 0; i < data.size(); i++) {
User user = new Student(data.get(i)[0]);
addUser(user);
}
}
public void saveUsers(String usersDir) throws IOException {
File myFile = new File(usersDir);
FileWriter fw = null;
try {
fw = new FileWriter(myFile);
} catch (IOException e) {
e.printStackTrace();
}
for(int i = 0; i < users.size(); i++){
if(users.get(i) != null) {
try {
if(users.get(i) instanceof Student) {
fw.write(String.format("%s,", users.get(i).getUsername()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
fw.close();
}
Resulting users.csv
student1,
student2,student3,