我正在制作一个应用程序,作为一个简单的教室图书馆,里面有书籍和用户。有教师和学生用户类型。我没有数据库,知道程序不能一直运行,所以在程序运行时更改/添加的信息应该在程序结束时保存。我面临的问题是它以我不理解的方式将信息写入 csv 文件。
Main.java 文件
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");
}
用户.csv
student1,
student2,
图书馆.java
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();
}
结果用户.csv
student1,
student2,student3,