Login example
/** Simulated login registration function
* The user enters the user name and password to match the user information in the file.
*
* File: config.properties
* Characteristics of stored data: each line is a user information
* scott=tiger
* admin=123456
*
*/
public class Test01 {
static File file = null;
static{
//load file
try {
file = new File("config.properties");
//When registering for the first time, the file is created
if(!file.exists()){
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace( );
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("1:Sign up-----2:Sign in");
int num = scan.nextInt( );
try {
String message = "";
if(num==1){
message = register(scan);
}else if(num==2){
message = login(scan);
}
System.out.println(message );
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Login function
* @param scan: Scanning class object
* @return the prompt message whether the login is successful
* @throws Exception
*/
public static String login(Scanner scan) throws Exception{
System.out.println("Please enter username:");
String username = scan.next();
System.out.println("Please enter Password:");
String password = scan.next();
/*
* Get all user information in the file
*/
Map<String,String> users = readToMap(file);
if(!users.containsKey(username)){
return "No such username";
}
String pwd = users.get(username);
if(!pwd.equals(password)){
return "Incorrect password";
}
return "Login successful";
}
/**
* Registration function
* @param scan: scan class object
* @return prompt information about whether the registration is successful
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static String register(Scanner scan) throws Exception{
System.out.println( "Please enter the username:");
String username = scan.next();
System.out.println("Please enter the password:");
String password = scan.next();
/*
* Read the user in the file Information, encapsulated into a Map object
* username is key
* password is value
*/
Map<String,String> users = readToMap(file);
/*
* Check if there is username in users
*/
if(users.containsKey(username)){
return "Username already exists";
}
/*
* Can register, save user information, and write files
*/
PrintWriter pw =
new PrintWriter(//Constructor
new OutputStreamWriter(/ /Character stream
new FileOutputStream(file,true),"utf-8"));//Byte stream
pw.println(username+"="+password);
pw.close();
return "Registration successful";
}
public static Map<String,String> readToMap(File file) throws Exception{
Map<String,String> users =
new HashMap<String,String>();
BufferedReader br =
new BufferedReader(//构造器
new InputStreamReader(//字符流
new FileInputStream(file),"utf-8"));//字节流
String line = ""; ,true
while((line=br.readLine())!=null){
//分析line
String[] a = line.split("=");
//存入users中
users.put(a[0], a[1]);
}
br.close();
return users;
}
}