Book类代码如下:
package com.msb.test15;
import java.io.Serializable;
public class Book implements Serializable {
private int bNo;
private String bName;
private String bAuthor;
public int getbNo() {
return bNo;
}
public void setbNo(int bNo) {
this.bNo = bNo;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getbAuthor() {
return bAuthor;
}
public void setbAuthor(String bAuthor) {
this.bAuthor = bAuthor;
}
public Book(int bNo, String bName, String bAuthor) {
this.bNo = bNo;
this.bName = bName;
this.bAuthor = bAuthor;
}
public Book() {
}
}
Test类代码如下:
package com.msb.test15;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
//老马书城集合版
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
while (true){
System.out.println("--------【欢迎来到老马书城】--------");
System.out.println("1.展示书籍");
System.out.println("2.上新书籍");
System.out.println("3.下架书籍");
System.out.println("4.退出应用");
Scanner input = new Scanner(System.in);
System.out.println("请录入你想要执行的功能的序号:");
int num = input.nextInt();
if (num == 1) {
System.out.println("展示书籍");
//从文件中读取list:
File f = new File("d:\\test.txt");
//流:
if(f.exists()==true){//文件存在
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
//将集合读取:
ArrayList list = (ArrayList) (ois.readObject());
for (int i = 0; i <list.size() ; i++) {
Book b = (Book)(list.get(i));
System.out.println(b.getbNo()+"---"+b.getbName()+"---"+b.getbAuthor());
}
}else{//文件不存在
System.out.println("当前没有上新书籍,请先上新书籍再进行书籍展示。");
}
}
if (num == 2) {
System.out.println("上新书籍");
System.out.println("请输入编号:");
int bNo = input.nextInt();
System.out.println("请输入书名:");
String bName = input.next();
System.out.println("请输入作者:");
String bAuthor = input.next();
Book b = new Book();
b.setbNo(bNo);
b.setbName(bName);
b.setbAuthor(bAuthor);
//将集合对象写到硬盘盘符文件去:
//文件;
File f = new File("d:\\test.txt");
if(f.exists()==true){//文件存在,证明之前的集合中已经有书籍
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
//将集合读取:
ArrayList list = (ArrayList) (ois.readObject());
list.add(b);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
//将list写出:
oos.writeObject(list);
//关闭流:
oos.close();
}else{//文件不存在, 证明是第一次上新书籍
ArrayList list = new ArrayList();
list.add(b);
//需要流:
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
//将list写出:
oos.writeObject(list);
//关闭流:
oos.close();
}
}
if (num == 3) {
System.out.println("下架书籍");
// int delnum = input.nextInt();
// for (int i = 0; i <list.size() ; i++) {
// Book b = (Book)(list.get(i));
// if(b.getbNo()==delnum){
// list.remove(b);
// System.out.println("书籍下架成功");
// break;
// }
// }
}
if (num == 4) {
System.out.println("退出应用");
break;
}
}
}
}