发布网友
共1个回答
热心网友
public interface Auth {
public void check(String name,String pwd,AuthResult result);
}
class AuthResult{
public String msg;// 结果信息
public boolean success;// 验证结果
public boolean isSuccess(){
return success;
}
public String getMsg(){
return msg;
}
}
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Auth1 implements Auth {
Map<String, String> data = new HashMap<String, String>();
@Override
public void check(String name,String pwd,AuthResult result) {
try {
// 加载用户名和密码
InputStream in = getClass().getResourceAsStream("Auth1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String temp = null;
while((temp = br.readLine()) != null){
data.put(temp.split(":")[0], temp.split(":")[1]);
}
if(data.get(name) == null){
result.success = false;
result.msg = "用户名错误";
return;
}
if(!pwd.equals(data.get(name))){
result.success = false;
result.msg = "密码错误";
return;
}
result.success = true;
result.msg = "auth success!";
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Auth2 implements Auth {
Map<String, String> data = new HashMap<String, String>();
@Override
public void check(String name,String pwd,AuthResult result) {
try {
// 加载用户名和密码
InputStream in = getClass().getResourceAsStream("Auth2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String temp = null;
int i = 1;
String temp1 = null;
while((temp = br.readLine()) != null){
if(i % 2 == 0){
data.put(temp1, temp);
} else {
temp1 = temp;
}
i++;
}
if(data.get(name) == null){
result.success = false;
result.msg = "用户名错误";
return;
}
if(!pwd.equals(data.get(name))){
result.success = false;
result.msg = "密码错误";
return;
}
result.success = true;
result.msg = "auth success!";
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Auth1 a1 = new Auth1();
Auth2 a2 = new Auth2();
Scanner sc = new Scanner(System.in);
String name = null;
String pwd = null;
System.out.println("enter name:");
name = sc.nextLine();
System.out.println("enter pwd:");
pwd = sc.nextLine();
AuthResult result = new AuthResult();
System.out.println("---Auth1---check");
a1.check(name,pwd,result);
if(result.isSuccess()){
System.out.println("auth success!");
} else {
System.out.println("auth fail! because " + result.getMsg());
}
System.out.println("---Auth2---check");
a2.check(name,pwd,result = new AuthResult());
if(result.isSuccess()){
System.out.println("auth success!");
} else {
System.out.println("auth fail! because " + result.getMsg());
}
}
}
文件与这些类同包下应该就能读到
Auth1.txt
name1:pwd1
name2:pwd2
Auth2.txt
name3
pwd3
name4
pwd4