You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
wang2/src/com/mathlearning/util/FileStorage.java

52 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.mathlearning.util;
import com.mathlearning.model.User;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FileStorage {
private static final String USER_DATA_EMAIL_FILE = "users_email.dat";
private static final String USER_DATA_USERNAME_FILE = "users_username.dat";
@SuppressWarnings("unchecked")
public static Map<String, User> loadUsersByEmail() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(USER_DATA_EMAIL_FILE))) {
return (Map<String, User>) ois.readObject();
} catch (FileNotFoundException e) {
// 文件不存在返回空Map
return new HashMap<>();
} catch (IOException | ClassNotFoundException e) {
System.err.println("加载用户数据失败: " + e.getMessage());
return new HashMap<>();
}
}
@SuppressWarnings("unchecked")
public static Map<String, User> loadUsersByUsername() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(USER_DATA_USERNAME_FILE))) {
return (Map<String, User>) ois.readObject();
} catch (FileNotFoundException e) {
// 文件不存在返回空Map
return new HashMap<>();
} catch (IOException | ClassNotFoundException e) {
System.err.println("加载用户数据失败: " + e.getMessage());
return new HashMap<>();
}
}
public static void saveUsers(Map<String, User> usersByEmail, Map<String, User> usersByUsername) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(USER_DATA_EMAIL_FILE))) {
oos.writeObject(usersByEmail);
} catch (IOException e) {
System.err.println("保存用户数据失败: " + e.getMessage());
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(USER_DATA_USERNAME_FILE))) {
oos.writeObject(usersByUsername);
} catch (IOException e) {
System.err.println("保存用户数据失败: " + e.getMessage());
}
}
}