12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package J20250802.demo04;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Properties;
- /**
- * @author WanJl
- * @version 1.0
- * @title UserServiceImpl
- * @description
- * @create 2025/8/2
- */
- public class UserServiceImpl implements UserService{
- /**
- * 用户注册
- *
- * @param user
- */
- @Override
- public void register(User user) {
- try {
- //File创建File文件对象
- File file=new File("D:/"+user.getUsername()+".properties");
- //先查一次又没有这个文件
- if (file.exists()){
- throw new UsernameDuplicateException("用户已存在");
- }
- //没有文件就创建
- file.createNewFile();
- //写入数据到文件
- FileWriter fw=new FileWriter(file);
- Properties prop=new Properties();
- //设置密码
- prop.setProperty("password", user.getPassword());
- //将集合的元素写入到文件
- prop.store(fw,null);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 用户登录
- *
- * @param username
- * @param password
- * @return 登录结果
- */
- @Override
- public String login(String username, String password) {
- //File创建File文件对象
- File file=new File("D:/"+username+".properties");
- //判断是否存在这个文件,不存在则抛出异常
- if (!file.exists()){
- throw new UsernameDuplicateException("用户不存在");
- }
- try {
- Properties prop=new Properties();
- prop.load(new FileReader(file));
- String pwd = prop.getProperty("password");
- return pwd.equals(password)?"登录成功":"登录失败,密码错误";
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "登录失败,密码错误";
- }
- }
|