BufferedReader将无法读取

时间:2016-09-07 21:35:39

标签: java file oop bufferedreader

我有一个程序,用户名和密码在文本文件中,文本文件如下所示:

election:12345

我有这段代码来读取文件

try {
    BufferedReader read=new BufferedReader(new FileReader("election_un_pass.txt"));
    String line="";

    while((line=read.readLine())!=null) {
        String [] info=line.split(":");

        if(info[0].matches(Login.uname) && info[1].matches(Login.pass)){
            new Main();
        } else {
            JOptionPane.showMessageDialog(null, "Username or Password might not be correct");
        }
        Login.txtUName.setText("");
        Login.txtPassword.setText("");
     }
} catch (Exception e1) {
    e1.printStackTrace();
}

每次运行程序时,即使我输入的用户名和密码都是正确的,Username or Password might not be correct消息仍会显示,new Main()也不会显示。

2 个答案:

答案 0 :(得分:0)

你可以:

  1. 了解如何使用您正在使用的IDE进行调试。使用调试模式,您可以一次执行一行代码,并查看每个点的变量值。
  2. 发生错误时增加日志记录信息
  3. 例如,您可以打印到控制台/日志/对话框:

    String msg = String.format("could not find user name: [%s] and password: [%s] in line: [%s]", Login.uname, Login.pass, line);
    

    显然,出于安全原因输入了不正确的值时,您不应该在任何地方打印预期的用户名和密码,但它可能是一种快速找出问题的方法:)它可能就像跟踪空白字符一样简单在某个地方某处或不正确的情况。

答案 1 :(得分:0)

您确定要使用String.matches(regex)进行比较吗?该参数被视为正则表达式,因此Login.unameLogin.pass值中的任何正则表达式元字符都将被解释为正则表达式。这意味着您的匹配可能会以您不期望的方式发挥作用。

我怀疑你真的想说:

if (info[0].equals(Login.uname) && info[1].equals(Login.pass)) {

代替。