java用io设计注册登入功能
时间: 2024-03-20 10:38:49 浏览: 16
好的,下面是 Java 中使用 IO 流实现注册登录功能的示例代码:
```java
import java.io.*;
public class RegisterLogin {
private static final String FILE_NAME = "users.txt"; // 存储用户信息的文件名
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("请选择功能:1.注册 2.登录 3.退出");
try {
String input = reader.readLine();
if (input.equals("1")) {
register(reader);
} else if (input.equals("2")) {
login(reader);
} else if (input.equals("3")) {
System.out.println("程序已退出!");
break;
} else {
System.out.println("输入有误,请重新选择!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void register(BufferedReader reader) throws IOException {
System.out.println("请输入用户名:");
String username = reader.readLine();
System.out.println("请输入密码:");
String password = reader.readLine();
PrintWriter writer = new PrintWriter(new FileWriter(FILE_NAME, true));
writer.println(username + "," + password);
writer.close();
System.out.println("注册成功!");
}
private static void login(BufferedReader reader) throws IOException {
System.out.println("请输入用户名:");
String username = reader.readLine();
System.out.println("请输入密码:");
String password = reader.readLine();
BufferedReader fileReader = new BufferedReader(new FileReader(FILE_NAME));
String line;
boolean found = false;
while ((line = fileReader.readLine()) != null) {
String[] parts = line.split(",");
if (parts[0].equals(username) && parts[1].equals(password)) {
found = true;
break;
}
}
fileReader.close();
if (found) {
System.out.println("登录成功!");
} else {
System.out.println("用户名或密码错误!");
}
}
}
```
上述代码中,`RegisterLogin` 类实现了注册登录功能。其中,`FILE_NAME` 常量指定了存储用户信息的文件名,用户信息以逗号分隔的形式存储在该文件中。在 `register` 方法中,用户输入用户名和密码,将其写入文件中;在 `login` 方法中,读取文件中的用户信息,与用户输入的用户名和密码进行比对。如果匹配成功,则登录成功,否则提示用户名或密码错误。