使用java将用户名和密码与文本文件中的数据进行比较

时间:2014-08-28 13:23:35

标签: java login text-files java.util.scanner

我想从文本文件中获取数据,如

qwer,qwer,qwer,qwer,wqer
qwer,qwer,qwer,qwer,wqer  

但是我不需要来自文本文件的所有数据,我只需要每行的前2个数据,即用户名和密码。 其他部分工作正常,只需要这个loginB按钮的代码。 usernameT passwordT是已创建的文本字段。

    loginB.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
       File loginf = new File("login.txt");

            try{
                Scanner read = new Scanner(loginf);
                read.useDelimiter(",");

                while(read.nextLine()){
                    String user = read.next();
                    String pass = read.next();
                     read.next();
                if(usernameT.getText().equals(user) && passwordT.getText().equals(pass) && admin.isSelected()){
                        new Menu();
                    }

                }
                JOptionPane.showMessageDialog(null, "Incorrect username or password");
                usernameT.setText("");
                passwordT.setText("");

                read.close();
            }
            catch (FileNotFoundException qwerty){
                    JOptionPane.showMessageDialog(null, "Can't find a text file");
            }
       }
    });

1 个答案:

答案 0 :(得分:1)

这有用吗:

boolean login = false;
while(read.nextLine() !=null){
   String user = read.next();
   String pass = read.next();
   read.next();
   if(usernameT.getText().equals(user) && passwordT.getText().equals(pass) && admin.isSelected()){
      login = true;
      break;                 
   }
}
if(login)
   new Menu();
else {
   JOptionPane.showMessageDialog(null, "Incorrect username or password");
   usernameT.setText("");
   passwordT.setText("");
}