文件解释/填充不正确

时间:2018-08-10 10:11:52

标签: java file binary

我刚刚学习了编码方法,并且正在尝试创建具有注册和登录功能的应用程序。下面的代码将用户名和密码添加到可以正常工作的文本文件中。

但是,当我尝试使用用户名和密码登录时,verifyLogin方法不起作用。如果我手动将密码和用户名添加到文本文件,则可以正常工作。我最好的猜测是有一些转换错误,但我不确定。

这是将用户名和密码添加到文件的代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String user = User.getSelectedItem().toString();
    String username = Username.getText();
    String password = Password.getText();
    String passwordConfirm = Password2.getText();

    if (user.trim().isEmpty() ||password.trim().isEmpty() || passwordConfirm.trim().isEmpty()){
        JOptionPane.showMessageDialog(rootPane, "Please fill out all fields");
    }
    else if(User.getSelectedItem().equals("Please Select")){
        JOptionPane.showMessageDialog(rootPane, "Please select wether you are a student ot a teacher");
    }
    else if(!password.equals(passwordConfirm)){
        JOptionPane.showMessageDialog(rootPane, "Please ensure the passwords you enter match");
    }
    else{
        if(User.getSelectedItem().equals("Student")){
            try{
                FileWriter writer = new FileWriter("Students.txt", true);
                writer.write(System.getProperty("line.separator"));
                writer.write(username);
                writer.write(",");
                writer.write(password);
                writer.close();
                JOptionPane.showMessageDialog(rootPane, "Success. You now have a students account");
                MainGUI  x = new MainGUI();
                x.setVisible(true);
                this.dispose();
            }
            catch(HeadlessException | IOException e){
                JOptionPane.showMessageDialog(rootPane, "Error");
            }
        }
        else{
            try{
                FileWriter writer = new FileWriter("Teachers.txt", true);
                writer.write(System.getProperty("line.separator"));
                writer.write(username);
                writer.write(",");
                writer.write(password);
                writer.close();
                JOptionPane.showMessageDialog(rootPane, "Success. You now have a teacher account");
                MainGUI  x = new MainGUI();
                x.setVisible(true);
                this.dispose();
            }
            catch(HeadlessException | IOException e){
                JOptionPane.showMessageDialog(rootPane, "Error");
            }  
        }
    }
}      

这是教师登录的代码:

public static void verifyLogin(String username, String password){
    boolean found = false;
    String tempUsername = "";
    String tempPassword = "";

    java.io.File file = new java.io.File("Teachers.txt");
    try{
        Scanner input = new Scanner(file);
        input.useDelimiter("[,\n]");

        while(input.hasNext() && !found){
            tempUsername = input.next();
            tempPassword = input.next();

            if (tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim())){
                found = true;
                TeacherOption  x = new TeacherOption();
                x.setVisible(true);
                this.dispose();
            }
            else{
                TeacherLoginError  x = new TeacherLoginError();
                x.setVisible(true);
                this.dispose();
            }
        }
        input.close();

    }
    catch(FileNotFoundException e){
        System.err.format("File does not exist \n");
    }
} 

2 个答案:

答案 0 :(得分:1)

在文件开头创建换行符会引起麻烦。假设您要输入3 usernamepassword

//empty line
Test1,TestPass1
Test2,TestPass2
Test3,TestPass3

在扫描仪中这样读取您的数据

user-1:

pass-1:Test1
user-2:TestPass1

pass-2:Test2
user-3:TestPass1

pass-3:Test3
user-4:TestPass3

pass-4:Test4
user-5:TestPass4
pass-5:

因此引起麻烦。

进行以下更改可以解决您的问题,

FileWriter writer = new FileWriter("Students.txt", true);
writer.write(username);
writer.write(",");
writer.write(password);
writer.write(System.getProperty("line.separator"));//add the new line after writing your user credentials
writer.close();

我还建议每行读取一次数据(以避免逻辑错误和更干净的数据提取),并尝试以加密格式存储密码

input.useDelimiter("\n");//take input per line
while(input.hasNext() && !found){
    String userDetails=input.next().trim();
    String credentialInfo[]=userDetails.split(",");
    if(!userDetails.isEmpty() 
            && credentialInfo.length==2) {//validate your input
        tempUsername = credentialInfo[0];
        tempPassword = credentialInfo[1];
        if (tempUsername.trim().equals(username.trim()) 
                && tempPassword.trim().equals(password.trim())){
              //rest of your code...

答案 1 :(得分:0)

我只是看了一下您的代码,我不敢相信我没有看到这一点:在您的while循环中,只要一组用户名和密码与输入不匹配,您就会显示TeacherLoginError

有问题吗?如果您有一个不匹配的集合,但在匹配的集合之前不匹配(这是更常见的情况),即使以后的迭代会找到正确的集合,您也会显示错误。因此,首先迭代并查找匹配的用户名和密码,然后在 循环之后,根据是否发现了某些内容来决定显示什么内容。

这是什么意思

假设您的文件包含以下内容:

user1,password1
user2,password2

现在,我输入“ user2”和“ password2”。您的代码(我们假设它正确读取了数据)首先针对user1,password1进行了检查,由于不匹配,因此您可以调用else-branch:

TeacherLoginError  x = new TeacherLoginError();
x.setVisible(true);
this.dispose();

您需要做些什么(重复使用代码):

//first look for a match only
boolean found = false;
while(input.hasNext() && !found){
  tempUsername = input.next();
  tempPassword = input.next();

  if (tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim())){
     found = true;
     break; //end the loop, you've already found a match
  }
}

//after the loop you act based on whether you found a match or not
if(found) {
  TeacherOption  x = new TeacherOption();
  x.setVisible(true);
} else {
  TeacherLoginError  x = new TeacherLoginError();
  x.setVisible(true);
}

this.dispose(); //this is called anyways so no need to have it twice