純 Java 控制台應用,以文字檔 res/Book.txt 作為資料存儲,實作「顯示全部、新增、查詢」三大核心功能。無資料庫依賴,適合初學者理解檔案 IO、集合、分層架構基本概念。
Book.txt 每行一筆,欄位以 # 分隔:
編號#書名#作者
B001#Java入門#張三
B002#Spring實戰#李四
public class Menu {
private final int MIN = 1, MAX = 3;
public void showMain() { System.out.println("1、顯示/2、新增/3、查詢"); }
public void showFind() { System.out.println("1、編號/2、書名/3、作者"); }
public int getChoice() {
Scanner sc = new Scanner(System.in);
System.out.print("輸入選項:");
int n = sc.nextInt();
return (n >= MIN && n <= MAX) ? n : -1;
}
}
public class Book {
private static final String FILE = "res/Book.txt";
// 顯示全部
public void listAll() {
try (Scanner in = new Scanner(new File(FILE))) {
while (in.hasNextLine()) parseAndPrint(in.nextLine());
} catch (FileNotFoundException e) { e.printStackTrace(); }
}
// 新增書籍(含編號唯一性檢查)
public void add() {
String record = buildRecord(); // 互動式輸入編號/書名/作者,檢查編號不重複
if (record.equals("@@!!")) return; // 重複則放棄
try (FileOutputStream fos = new FileOutputStream(FILE, true)) {
fos.write(record.getBytes());
System.out.println("新增成功");
} catch (IOException e) { e.printStackTrace(); }
}
// 多條件查詢
public void find() {
Menu m = new Menu(); m.showFind();
int type = m.getChoice();
Scanner sc = new Scanner(System.in);
String keyword = "";
switch (type) {
case 1: System.out.print("輸入編號:"); keyword = sc.next(); search(0, keyword); break;
case 2: System.out.print("輸入書名:"); keyword = sc.next(); search(1, keyword); break;
case 3: System.out.print("輸入作者:"); keyword = sc.next(); search(2, keyword); break;
}
}
private void search(int fieldIndex, String keyword) {
try (Scanner in = new Scanner(new File(FILE))) {
while (in.hasNextLine()) {
String[] fields = in.nextLine().trim().split("#");
if (fields[fieldIndex].equals(keyword)) print(fields);
}
} catch (FileNotFoundException e) { e.printStackTrace(); }
}
private String buildRecord() {
Scanner sc = new Scanner(System.in);
System.out.print("輸入編號:"); String id = sc.next();
if (exists(0, id)) { System.out.println("編號已存在"); return "@@!!"; }
System.out.print("輸入書名:"); String name = sc.next();
System.out.print("輸入作者:"); String author = sc.next();
return id + "#" + name + "#" + author + "#\n";
}
private boolean exists(int idx, String val) {
try (Scanner in = new Scanner(new File(FILE))) {
while (in.hasNextLine()) if (in.nextLine().split("#")[idx].equals(val)) return true;
} catch (FileNotFoundException e) { e.printStackTrace(); }
return false;
}
private void parseAndPrint(String line) {
for (String s : line.trim().split("#")) System.out.println(s);
System.out.println("*********************");
}
}
public class ManageBook {
public static void main(String[] args) {
Menu menu = new Menu();
Book book = new Book();
while (true) {
menu.showMain();
switch (menu.getChoice()) {
case 1: book.listAll(); break;
case 2: book.add(); break;
case 3: book.find(); break;
default: System.out.println("輸入錯誤");
}
}
}
}
| 亮點 | 不足/可改進 |
|---|---|
| 分層清晰,職責單一 | 檔案鎖/併發無處理 |
| 檔案 IO 操作規範 | 無修改/刪除功能 |
| 編號唯一性檢查 | 查詢僅支援精確匹配 |
| 資源 try-with-auto-close | 無異常統一處理機制 |