import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
class Book implements Serializable {
String name;
String author;
String press;
int level;
double price;
public Book(String name, String author, String press, int level, double price) {
this.name = name;
this.author = author;
this.press = press;
this.level = level;
this.price = price;
}
@Override
public String toString() {
return name + " " + author + " " + press + " " + level + " " + price;
}
}
class Library implements Serializable{
ArrayList<Book> al = new ArrayList<>();
void addBook(Book b) {
al.add(b);
}
void persist() throws IOException {
File file = new File("src\\books.dat");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
for (int i = 0; i < al.size(); i++) {
fw.write(al.get(i).toString());
fw.write("\n");
}
fw.close();
// FileOutputStream fos=new FileOutputStream(file);
// ObjectOutputStream oos=new ObjectOutputStream(fos);
// oos.writeObject(this);
// oos.close();
}
public Book[] restore() throws IOException {
ArrayList<Book> temp = new ArrayList<>();
File file = new File("src\\books.dat");
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
for (;;) {
String str = in.readLine();
if (str == null) {
break;
}
String[] split = str.split(" ");
temp.add(new Book(split[0], split[1], split[2], Integer.parseInt(split[3]), Double.parseDouble(split[4])));
}
in.close();
Book[] array = temp.toArray(new Book[temp.size()]);
// FileInputStream fis=new FileInputStream(file);
// ObjectInputStream ois=new ObjectInputStream(fis);
// Book[] array = null;
// try {
// Library library = (Library) ois.readObject();
// return library.al.toArray(new Book[al.size()] );
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
return array;
}
}
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
Library L = new Library();
L.addBook(new Book("语文", "11", "11", 1, 100));
L.addBook(new Book("数学", "22", "22", 2, 200));
L.addBook(new Book("英语", "33", "33", 3, 300));
L.persist();
Book b[] = L.restore();
for (int i = 0; i < b.length; i++) {
System.out.println(b[i].toString());
}
scanner.close();
}
}
图书馆持久化 (40 分)(非序列化方式) 构造图书类,包含名称(字符串)、作者(字符串)、
最新推荐文章于 2021-08-19 16:46:21 发布