Person 類別封裝屬性與驗證邏輯。HashMap<Integer, Person> 記憶體存儲。id\tname\tsex\tage。package azhi0901;
public class Person {
private static int total = 1; // 自動編號
private int id;
private String name;
private String sex;
private int age;
public Person(int id, String name, String sex, int age) {
this.id = total++;
if (name == null) throw new RuntimeException("姓名不能為空");
this.name = name;
if (!"男".equals(sex) && !"女".equals(sex)) throw new RuntimeException("性別只能是男/女");
this.sex = sex;
if (age < 0 || age > 200) throw new RuntimeException("年齡範圍 0-200");
this.age = age;
}
// getter/setter 同樣加入驗證...
}
// 載入
private static void loadData() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("F:/HRMS.txt")));
String line;
while ((line = br.readLine()) != null) {
String[] ss = line.split("\t");
Person p = new Person(Integer.parseInt(ss[0]), ss[1], ss[2], Integer.parseInt(ss[3]));
map.put(p.getId(), p);
}
br.close();
}
// 存檔
public static void saveData() throws Exception {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("F:/HRMS.txt")), true);
for (Integer id : map.keySet()) {
Person p = map.get(id);
pw.println(p.getId() + "\t" + p.getName() + "\t" + p.getSex() + "\t" + p.getAge());
}
pw.close();
}
Map 做鍵值存儲FileInputStream → InputStreamReader → BufferedReaderthrows Exception + try-catchtotal 未同步,新增會重複。F:/HRMS.txt 應改為相對路徑或配置。