Java:在数组中搜索字符串的文件

时间:2017-03-23 15:43:09

标签: java arrays

我正在使用文本文件创建Java用户系统,我正在尝试使用相同的用户名无法注册两次。它完全忽略了它并且无论如何都允许创建。

我下面的代码是:

static boolean checkUsername(String u) { //Check the username and password
        boolean userFound = false;
         try { //Try and read our user file
             Scanner loginRead = new Scanner(loginFile); //Load the file into the scanner

             loginRead.useDelimiter("|"); //Split each set of user data into an array with |
             try {
                 if(loginRead.nextLine() ==null) {
                     return false;
                 } else {
                     while(loginRead.nextLine() !=null){ //Run line by line until we find this MF
                         String user_r = loginRead.next(); //loginRead[0] = Username
                         loginRead.next(); //Read the line

                         if(u.equals(user_r)){ //If we have a match
                              userFound=true;
                              break;   //Break the login script because we've struck gold
                         }
                     }
                 }
             } catch(NoSuchElementException e) {
                 return false;
             }


         } catch (FileNotFoundException exceptionText) { //We couldn't find the user file.
             System.out.println("User file error");

         }

         return ((userFound==true) ? true : false); //Short hand if statement
         //to tell us if we found that user

    }

用户文件:

username|pwhash|fname|lname
username|pwhash|fname|lname
username|pwhash|fname|lname
username|pwhash|fname|lname

我哪里错了?

1 个答案:

答案 0 :(得分:0)

非常非常晚。但是我重新做了代码,这就是我的目标,对于其他任何想知道的人来说:

static boolean checkUsername(String u) throws IOException { //We use this function when registering a user, to make sure they don't already exist
        boolean userFound = false; //Our boolean for if the user exists
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("./loginData.dat")); //Load our loginData.dat file into the buffer
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for (String line = br.readLine(); line != null; line = br.readLine()) { //Read the file line by line
            String[] userDataNew=line.toString().split("\\|"); //Split our line up into an array using |

            if(userDataNew[0].equals(u)) { //We've found their username already
                userFound = true; //Set our user found bool to true
                break; //Break out of the foor loop
            }
        }
        return userFound; //Return true/false 
}