import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Two {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
//创建一个文件保存数据
File file = new File("C:\\Users\\cdlx2016\\Desktop\\user.txt");
file.createNewFile();
System.out.println("请选择功能: "+"1.登录 "+" 2.注册");
int number = sc.nextInt();
switch (number) {
case 1:
importFile(file);
break;
case 2:
output(file);
break;
default:
System.out.println("输入错误!");
break;
}
}
//登录方法
public static void importFile(File file) throws IOException {
System.out.print("请输入用户名: ");
String neme = sc.next();
System.out.print("请输入密码: ");
String password = sc.next();
//字符输入流
FileReader importFile = new FileReader(file);
//创建缓冲区
BufferedReader read = new BufferedReader(importFile);
String str = null;
while((str = read.readLine()) != null){
if(str.compareTo(neme+" "+password) == 0){
System.out.print("登录成功! ");
read.close();
return;
}
}
System.out.print("用户名或密码输入错误,请重新输入!");
read.close();
}
//注册方法
public static void output(File file) throws IOException {
System.out.print("请输入用户名: ");
String neme = sc.next();
//遍历所有数据,判断是否有重复的用户
//字符输入流
FileReader importFile = new FileReader(file);
//创建缓冲区
BufferedReader read = new BufferedReader(importFile);
String str = null;
while((str = read.readLine()) != null){
str = str.substring(0, str.indexOf(" "));
if(str.equals(neme)){
System.out.print("该用户已存在,请重新注册!");
return;
}
}
System.out.print("请输入密码: ");
String password = sc.next();
//字符输出流
FileWriter output = new FileWriter(file,true);
//创建缓冲区
BufferedWriter writer = new BufferedWriter(output);
//存入数据库
writer.write("\r\n"+neme+" "+password);
writer.flush();
//output.write();
System.out.print("注册成功! ");
//关闭资源
writer.close();
read.close();
}
}