Scala项目(图书管理系统)
5、dao
BookDAO
package org.app
package dao
import org.app.models.BookModel
import scala.collection.mutable.ListBuffer
// 图书,数据操作层
class BookDAO {
// 加载图书。从文件中读入
def loadBooks(): ListBuffer[BookModel] = {
val books = new ListBuffer[BookModel]()
val source = scala.io.Source.fromFile("books.txt")
for(line <- source.getLines()){
val Array(id,name,author,available) = line.split(",")
// 实例化一本书,保存到List
books += BookModel(id.toInt,name,author,available.toBoolean)
}
// 关闭连接
source.close()
books
}
// 保存图书。将图书写入文件
def saveBooks(books: ListBuffer[BookModel]): Unit = {
val writer = new java.io.PrintWriter(new java.io.File("books.txt"))
for(book <- books){
writer.println(book.id + "," + book.name + "," + book.author + "," + book.available)
}
writer.close()
}
}
BorrowRecordDAO
package org.app
package dao
import org.app.models.BorrowRecordModel
import scala.collection.mutable.ListBuffer
import scala.io.Source
class BorrowRecordDAO {
// 读出借阅记录
def loadBorrowRecords(): ListBuffer[BorrowRecordModel] = {
val borrowRecords = ListBuffer[BorrowRecordModel]()
val lines = Source.fromFile("borrow_records.txt")
for(line <- lines.getLines()){
val Array(userName,bookID,bookName,borrowDate,returnDate) = line.split(",")
borrowRecords += BorrowRecordModel(userName,bookID.toInt,bookName,borrowDate,Some(returnDate))
}
borrowRecords
}
// 写入借阅记录
def saveBorrowRecords(records: ListBuffer[BorrowRecordModel]): Unit = {
val writer = new java.io.PrintWriter("borrow_records.txt")
for(record <- records){
writer.println(record.userName+","+record.bookID+","+record.bookName+","+record.borrowDate+","+record.returnDate.getOrElse(""))
}
writer.close()
}
}
UserDAO
package org.app
package dao
import org.app.models.UserModel
import scala.collection.mutable.ListBuffer
class UserDAO {
// 加载所有的用户
def loadUsers(): ListBuffer[UserModel] = {
val users = new ListBuffer[UserModel]()
val source = scala.io.Source.fromFile("users.txt")
for(line <- source.getLines()){
val Array(username, password, role) = line.split(",")
// 实例化一个用户,保存到List
users += UserModel(username, password, role)
}
// 关闭连接
source.close()
users
}
}
原文地址:https://blog.csdn.net/2401_84653595/article/details/144656780
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!