实现用户注册与登录功能
(1)注册:将用户信息保存到磁盘
登录:将用户信息从磁盘中读取出来,并输出到控制台
package test2;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class testU {
public static void main(String[] args) throws IOException {
boolean flag=true;
while(flag) {
System.out.println("请选择功能1=注册,2=登录,3=退出");
int a=new Scanner(System.in).nextInt();
switch(a) {
case 1:
System.out.print("请输入用户名");
String name=new Scanner(System.in).next();
System.out.print("请输入密码");
String password=new Scanner(System.in).next();
//创建并实例化FileWriter对象
FileWriter f=new FileWriter("D:\\上课\\"+name+".txt");
f.write(password);
f.close();
System.out.println("注册成功");
break;
case 2:
File f2=new File("D:\\上课");
File[] fs = f2.listFiles();
System.out.println("请输入用户名");
String name1=new Scanner(System.in).next();
//遍历该文件夹下的所有文件判断是否存在该用户
boolean isok=false;
for(File s:fs) {
if((name1+".txt").equals(s.getName())) {
isok=true;
}
}
if(isok==true) {
System.out.println("请输入密码");
String pass2=new Scanner(System.in).next();
FileReader f3=new FileReader("D:\\上课\\"+name1+".txt");
int k=0;
String str="";
while((k=f3.read())!=-1) {
str+=(char)k;
}
f3.close();
if(pass2.equals(str)) {
System.out.println("登录成功");
}else {
System.out.println("密码错误,请重新输入");
}
}else {
System.out.println("此用户尚未注册,请先注册再登录");
}
break;
case 3:
System.out.println("退出程序");
flag=false;
break;
default :
System.out.println("输入有误,请重新输入");
break;
}
}
}
}