我有一个文本文件,其中的名称和密码以 : 分隔。
user1:pwd1
user2:pwd2
在登录页面中,如果用户提供正确的用户名和密码,您将进入欢迎页面。但我没有正确理解这一点。我得到的输出是
user1
pwd1
inside try
user1
pwd1
true
welcome user1
user2
pwd2
false
not equal
我的代码如下。
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.regex.*;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;
public class TextFile {
/**
* @param args
*/
public void getNamePwd(String name, String pwd) {
// TODO Auto-generated method stub
System.out.println(name);
System.out.println(pwd);
String[] splitVals=null;
try{
System.out.println("inside try");
String strLine;
BufferedReader br = new BufferedReader(new FileReader("D:\\test\\text.txt"));
while((strLine=br.readLine())!=null){
splitVals=strLine.split(":");
for(int i=0;i<splitVals.length;i=i+2){
System.out.println(splitVals[i].toString());
System.out.println(splitVals[i].toString());
String nameUser=splitVals[i].toString();
String passWord=splitVals[i+1].toString();
System.out.println(name.equals(nameUser));
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
}
else{
System.out.println("not equal");
}
}
}
}catch(Exception e){
}
}
}
请帮助我..
最佳答案
我怀疑您在找到用户名/密码匹配后就想停止查找...为此,您必须在匹配时打破循环。为此,您需要执行以下操作:
readLoop:
while((strLine=br.readLine())!=null){
// ...
String[] splitVals = strLine.split(":");
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
break readLoop;
}
// ...
}
<小时/>
此外,我不知道为什么你需要这个循环:
for(int i=0;i<splitVals.length;i=i+2)
回想一下,您逐行读取了该文件。也就是说,分割后的数组将包含当前行的用户名和密码。
要打印用户名/密码,您可以执行以下操作:
System.out.printf("Username: %s, Password: %s%n", splitVals[0], splitVals[1]);
<小时/>
我可能会使用扫描仪
来解决它。像这样的事情:
import java.io.*;
import java.util.Scanner;
public class TextFile {
public static void main(String[] args) throws FileNotFoundException {
if (userPassOk("hello", "world"))
System.out.println("Welcome");
else
System.out.println("Get out!");
}
private static boolean userPassOk(String user, String pass)
throws FileNotFoundException {
Scanner s = new Scanner(new File("test.txt"));
while (s.hasNextLine()) {
String[] userPass = s.nextLine().split(":");
if (userPass[0].equals(user) && userPass[1].equals(pass))
return true;
}
return false;
}
}
关于java - 读取文本文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4814614/