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.
50 lines
2.1 KiB
50 lines
2.1 KiB
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) {
|
|
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) {
|
|
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());
|
|
}
|
|
}
|
|
} |