DomLip DomLip - 1 year ago 52
Java Question

Java: Search file for string in array

I'm making a user system in Java using text files and i'm trying to make it so that the same username can't register twice. It completely ignores it and allows for the creation anyway.

The code I have below is:

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

}


User file:

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


Where am I going wrong?

Answer Source

Very, very late. But I re-did the code and here is what I went with, for anyone else wondering:

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 
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download