java从textfile

时间:2016-12-24 12:05:46

标签: java file java.util.scanner

我从文本文件中读取时出现此问题,其中凭据用新行分隔,例如新段落,我不知道如何阅读它们。以下是我的登录按钮代码:

private class Login implements ActionListener{
    public void actionPerformed(ActionEvent Login){  
        Boolean login = false;
        file = new File("Member Details.txt");
        try {
            read = new Scanner(file);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BTRSMain.class.getName()).log(Level.SEVERE, null, ex);
        }
        String user = read.next();
        String pass = read.next();
        if(loginpage.UsernameTB.getText().equals(user) && loginpage.PasswordTB.getText().equals(pass)){
           login = true;}
        if(login)
        {
            loginpage.frame.setVisible(false);
            mainmenupage.frame.setVisible(true);
        }
        else
        {
           JOptionPane.showMessageDialog(null, "Incorrect username or password! Please re-enter!");
           loginpage.UsernameTB.setText("");
           loginpage.PasswordTB.setText("");
        }
        }
    }

用户注册后,会员详细信息(即用户名和密码)将保存在文本文件中,每个文件都在新行the text file image here中,在登录页面中,第一个用户名和密码可以请阅读,但稍后,第二个用户名和密码无法读取,我该怎么办?如何在新行中读取该代码?

文本文件的文字如下:
第一行(第一个用户名):lulu
第二行(第一个密码):lili
第三行(第二个用户名):lili
第四行(第二个密码):lulu

它可以读取第一个用户名和密码,但不能读取第二个用户名和密码。

1 个答案:

答案 0 :(得分:1)

您只需阅读一个用户名 - 密码对。您需要阅读整个文件。例如,如果我们每次保持当前读取文件的设计,你可以做这样的事情(我将登录检查逻辑分离到另一种方法。原始方法可以调用它并弹出相关消息):

private boolean canLogin(String user, String password) {
    try (Scanner read = new Scanner(new File("Member Details.txt"))) {
        while (read.hasNext()) {
            String readUser = read.next();
            String readPassword = read.next(); // Assume the file is well-formed

            // If it's the right user, check the password
            // If not, continue reading the file
            if (user.equals(readUser)) {
                return password.equals(readPassowrd);
            }
    }
    catch (FileNotFoundException ex) {
        Logger.getLogger(BTRSMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
相关问题