Java練習-003
package com.java.learing;
import java.io.BufferedReader;
import java.io.File;
/**
* @author YuFeifei
* @version 2017年11月17日 下午17:03:45
* 類說明:讀取txt內容,存在map中,之後輸入用戶和密碼模擬登陸
*/
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 File(filePath);//文件路徑
Map<String,String> mapTmp = new HashMap<String,String> ();//用來存儲讀取的用戶名和密碼
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){
//用split方法將用戶名和密碼分開
String str[] = lineTxt.split(",");
//將讀取出的數據存在mapTmp中
mapTmp.put(str[0], str[1]);
}
return mapTmp;
}else{
System.out.println("文件不存在!");
}
}catch(Exception e){
System.out.println("文件讀取錯誤!");
}
return null;
}
}
class LogIn{
public void Login(){
System.out.println("輸入用戶名:");
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("輸入密碼:");
Scanner scan2 = new Scanner(System.in);
String password = scan2.nextLine();
if(tmp.readTxt(filePath).containsValue(password) ){
System.out.println("登錄成功");
}
else{
System.out.println("密碼錯誤!");
}
}
else{
System.out.println("用戶名不存在!");
}
}
}
public class TestDemo08 {
public static void main(String agrs[]){
LogIn login = new LogIn();
login.Login();
}
}
Java練習-003