java图书馆
进阶:连接数据库存储数据,现在这个版本是在本地存储。
涉及知识点
- IO输入,输出流
学习产出:
在这里插入package test;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
while (true) {
System.out.println("1.展示书籍");
System.out.println("2.上新书籍");
System.out.println("3.下架书籍");
System.out.println("4.退出应用");
Scanner sc = new Scanner(System.in);
System.out.print("请输入序号;");
int choice = sc.nextInt();
if (choice == 1) {
System.out.println("1.展示书籍");
File f = new File("D:\\book.txt");
if (f.exists()) {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList list = (ArrayList) (ois.readObject());
for (int i=0;i<=list.size()-1;i++){
Book b = (Book) (list.get(i));
System.out.println(b.getbNo()+"---"+b.getbName()+"---"+b.getbAuto());
}
}else {
System.out.println("文件不存在");
}
}
if (choice == 2) {
System.out.println("2.上新书籍");
System.out.println("请输入录入书籍序号");
int bNo=sc.nextInt();
System.out.println("请输入录入书籍名称");
String bName=sc.next();
System.out.println("请输入录入书籍作者");
String bAuto=sc.next();
Book x = new Book();
x.setbNo(bNo);
x.setbName(bName);
x.setbAuto(bAuto);
File f = new File("D:\\book.txt");
if (f.exists()) {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList list = (ArrayList) (ois.readObject());
list.add(x);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
}else {
ArrayList list = new ArrayList();
list.add(x);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
}
}
if (choice == 3) {
System.out.println("3.下架书籍");
System.out.println("输入要删除的书籍序号");
int a = sc.nextInt();
File f = new File("D:\\book.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList list = (ArrayList) (ois.readObject());
for (int i=0;i<=list.size()-1;i++){
Book b = (Book) (list.get(i));
if(a==b.getbNo()){
list.remove(b);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
System.out.println("书籍删除成功!");
}else {
System.out.println("未找到该书籍!");
}
}
}
if (choice == 4) {
System.out.println("4.退出应用");
break;
}
}
}
}
在这里插入代码package test;
import java.io.Serializable;
public class Book implements Serializable {
private int bNo;
private String bName;
private String bAuto;
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 getbAuto() {
return bAuto;
}
public void setbAuto(String bAuto) {
this.bAuto = bAuto;
}
public Book(int bNo, String bName, String bAuto) {
this.bNo = bNo;
this.bName = bName;
this.bAuto = bAuto;
}
public Book() {
}
}