Package com.java.learing;
Import Java.io.BufferedReader;
Import Java.io.File;
/**
* @author Yufeifei
* @version November 17, 2017 17:03:45
* Class Description: Read txt content, exist in map, then enter user and password simulation login
*/
Import java.io.*;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Scanner;
Class readtxtfile{
public static map<string,string> Readtxt (String filePath) {
try{
File File = new (FilePath);//Files path
map<string,string> maptmp = new hashmap<string,string> ();//used to store the read user name and password
if (File.isfile () && file.exists ()) {
InputStreamReader ISR = new InputStreamReader (new FileInputStream (file), "Utf-8");
BufferedReader br = new BufferedReader (ISR);
String linetxt = null;
while ((Linetxt = Br.readline ()) = null) {
Separate username and password with split method
String str[] = Linetxt.split (",");
The data that is being read out exists in maptmp
Maptmp.put (Str[0], str[1]);
}
return maptmp;
}else{
SYSTEM.OUT.PRINTLN ("file does not exist!) ");
}
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("File read error! ");
}
return null;
}
}
Class login{
public void Login () {
System.out.println ("Enter user name:");
Scanner scan1 = new Scanner (system.in);
String username = Scan1.nextline ();
Readtxtfile tmp = new Readtxtfile ();
String FilePath = "D:\\user.txt";
;
if (Tmp.readtxt (FilePath). ContainsKey (username)) {
System.out.println ("Enter password:");
Scanner scan2 = new Scanner (system.in);
String password = scan2.nextline ();
if (Tmp.readtxt (FilePath). Containsvalue (password)) {
SYSTEM.OUT.PRINTLN ("Login Successful");
}
else{
SYSTEM.OUT.PRINTLN ("Bad password!") ");
}
}
else{
System.out.println ("User name does not exist! ");
}
}
}
public class TestDemo08 {
public static void Main (String agrs[]) {
Login login = new login ();
Login. Login ();
}
}
Java Exercise-003