定义两个类 Book, BookDAO, 其中Book类用于封装一个书籍对象,BookDAO中实现对于文本文件Book.txt的增加、修改、删除和查询方法(至少4种查询方法)。用
时间: 2024-11-20 11:37:26 浏览: 3
JAVA类引用接口的多继承完成图书管理系统
首先,让我们定义`Book`类,它将包含书籍的基本信息:
```java
public class Book {
private String title;
private String author;
private int publicationYear;
// 构造函数
public Book(String title, String author, int publicationYear) {
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
}
// getter和setter方法
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public int getPublicationYear() { return publicationYear; }
public void setPublicationYear(int publicationYear) { this.publicationYear = publicationYear; }
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", publicationYear=" + publicationYear +
'}';
}
}
```
接下来,我们创建`BookDAO`类,该类将负责对`Book.txt`文件的操作,包括增删改查功能:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class BookDAO {
private static final String FILE_NAME = "Book.txt";
// 数据存储列表
private static List<Book> bookList = new ArrayList<>();
// 读取文件并填充bookList
public static void loadBooks() {
try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
Book book = new Book(data[0], data[1], Integer.parseInt(data[2]));
bookList.add(book);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 添加书籍到文件
public static void addBook(Book book) {
bookList.add(book);
saveBooks();
}
// 更新书籍(假设通过书名查找)
public static void updateBook(String title, String author, int year) {
for (int i = 0; i < bookList.size(); i++) {
if (bookList.get(i).getTitle().equals(title)) {
bookList.set(i, new Book(title, author, year));
break;
}
}
saveBooks();
}
// 删除书籍(同样通过书名查找)
public static void deleteBook(String title) {
bookList.removeIf(book -> book.getTitle().equals(title));
saveBooks();
}
// 查询方法
public static Book findBookByTitle(String title) {
return bookList.stream()
.filter(book -> book.getTitle().equals(title))
.findFirst()
.orElse(null);
}
public static List<Book> getAllBooks() {
return bookList;
}
// 保存数据到文件
private static void saveBooks() {
try (PrintWriter pw = new PrintWriter(new FileWriter(FILE_NAME, true))) {
for (Book book : bookList) {
pw.println(book.getTitle() + "," + book.getAuthor() + "," + book.getPublicationYear());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,`loadBooks()`方法用于初始化文件内容,而其他方法如`addBook()`、`updateBook()`、`deleteBook()`以及`findBookByTitle()`分别实现了增加、修改、删除和查询操作。请注意,这个设计假定文件中的每一行代表一本书的信息,并且使用逗号分隔标题、作者和年份。
阅读全文