import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOE ...
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();
}
}