求助:Java 如何分行读取txt里内容进行登入身份验证~!
有个anguage.txt 里面记录着用户的帐号和密码
格式是: aaa 111
bbb 222
ccc 333
如何才能把里面的帐号和密码 分别读出 然后在用户登入框里里进行匹配验证,成功的话则登入成功,不成功的话则跳出登入失败~!
希望大家能帮帮忙 谢谢啦
------解决方案--------------------全部读下来分离字符串?
------解决方案--------------------就是文件读取的操作。
把读出的记录分离开后,保存在一个set中,就ok。
另外,为什么不改用xml文件?或者数据库?
------解决方案--------------------下面是一个简单的例子:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Login {
private BufferedReader reader;
public Login() {
init();
}
private void init() {
try {
reader = new BufferedReader(new FileReader(new File( "anguage.txt ")));
} catch (Exception e) {
}
}
public boolean checkUser(String username, String password) {
try {
String str = reader.readLine();
while(str != null) {
String[] info = str.split( " ");
System.out.println(info[0].trim() + " " + info[1].trim());
if(info[0].trim().equals(username) && info[1].trim().equals(password)) {
return true;
}
str = reader.readLine();
}
} catch (Exception e) {
System.out.println( "Error occured when verify user ");
}
return false;
}
public static void main(String[] args) {
if(args == null || args.length < 2) {
System.out.println( "Usage: java Login username password: \n e.g. java Login tony 657891 ");
return;
}
Login login = new Login();
if(login.checkUser(args[0], args[1])) {
System.out.println( "Congratulations! Login successfully ");
} else {
System.out.println( "Incorrect username or password! ");
}
}
}
------解决方案--------------------FileInputStream ss = new FileInputStream(fileUrl);
byte[] s = new byte[(int)ss.getChannel().size()];
ss.read(s);
String fileText = new String(s);
String[] users = fileText.split( "\r\n ");//users数组每个元素存放一个用户(一行)
------解决方案--------------------不用分段读,你全读出来放到字符串里面。看好格式,把你从输入框里得到用同样的格式看看再不在这个大字符串里不就行了
------解决方案--------------------Properties props = new Properties();
props.load(new FileInputStream( "filename.properties "));
String Id= props.getProperty( "userId ");
String Password= props.getProperty( "passWord ");
filename.properties格式为
userId=root;
password=111111;
如果LZ有多个用户的话,建议用DOM4J解决
try{
SAXReader reader = new SAXReader();
Document document = reader.read( "c:/Demo.txt ");
Element root = document.getRootElement();
for ( Iterator node = root.elementIterator(); node.hasNext(); ) {
// CompanyBean a=new CompanyBean();
Element element = (Element) node.next();
Attribute attribute = (Attribute) element.attribute( "value ");