用Java语言编写程序使用对象输入/输出流完成用户注册登录界面,User类(用户名,密码)保存在工程文件夹下res\password.txt中 。(仿P204-例题10-12),使用消息框给出相关信息(自学JOptionPane的showMessageDialog方法的使用)
时间: 2024-01-25 16:02:35 浏览: 24
好的,我理解了你的问题。下面是Java代码实现:
```java
import java.io.*;
import javax.swing.*;
class User implements Serializable {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
public class LoginDemo {
public static void main(String[] args) {
String filePath = "res/password.txt";
File file = new File(filePath);
// 创建文件夹
File folder = new File("res");
if (!folder.exists()) {
folder.mkdirs();
}
try {
// 创建文件
if (!file.exists()) {
file.createNewFile();
}
// 读取用户信息
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
User user = (User) in.readObject();
in.close();
fileIn.close();
// 登录对话框
String inputUsername = JOptionPane.showInputDialog("请输入用户名:");
String inputPassword = JOptionPane.showInputDialog("请输入密码:");
// 校验用户名密码
if (inputUsername.equals(user.getUsername()) && inputPassword.equals(user.getPassword())) {
JOptionPane.showMessageDialog(null, "登录成功!");
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误!");
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 注册对话框
String username = JOptionPane.showInputDialog("请输入要注册的用户名:");
String password = JOptionPane.showInputDialog("请输入要注册的密码:");
User newUser = new User(username, password);
try {
// 写入用户信息
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(newUser);
out.close();
fileOut.close();
JOptionPane.showMessageDialog(null, "注册成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
代码中的 `User` 类是一个简单的 JavaBean,包含用户名和密码两个属性。`LoginDemo` 类实现了用户登录和注册的功能。
程序会先读取工程文件夹下的 `res/password.txt` 文件,如果文件不存在则会创建新文件。读取到的 `User` 对象会用于登录校验。
登录校验和注册都使用了 `JOptionPane` 类的 `showInputDialog` 和 `showMessageDialog` 方法。前者用于输入用户名和密码,后者用于展示校验结果和注册成功提示。
注意,需要在类定义前添加 `import java.io.*;` 和 `import javax.swing.*;` 以引入必要的类。