How to read line by line by using FileReader
here is my code to read from a file :
String line;
try {
BufferedReader bufferreader = new BufferedReader(new FileReader("C:\\Users\\ahmad\\Desktop\\aaa.TXT"));
while ((line = bufferreader.readLine()) != null) {
/**
Your implementation
**/
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Assuming we have a file with username
and hash
stored as follows:
Hello World
Test Test
DumbUser 12345
User sjklfashm-0998()(&
and we want to use the first word in every line as username
and the second as password
/hash
. Then the idea is:
- Read a line
- Split the line into parts at " "
- Compare the first part to
username
and the second topass
- If there is a match return true, else start over
Which results in this code:
public boolean checkPassword(String username, String pass) {
// if there is no username or no password you can not log in
if(username == null || pass == null){ // diff
return false; // diff
} // diff
try {
FileReader inFile = new FileReader(PASSWORD_FILE);
BufferedReader inStream = new BufferedReader(inFile);
String inString;
while ((inString = inStream.readLine()) != null) {
// we split every line into two parts separated by a space " "
String usernameHash[] = inString.split(" "); // diff
// if there are more or less than two parts this line is corrupted and useless
if(usernameHash.length == 2 // diff
&& username.equals(usernameHash[0]) // diff
&& pass.equals(usernameHash[1])){ // diff
// if username matches the first part and hash the second everything is goo
return true; // diff
} // diff
}
inStream.close();
}catch (IOException e) {
e.printStackTrace();
}
return false;
}
I marked the parts where my code differs from yours with // diff