Am trying to read an object from a text file using scanner, but my problem is i cannot access the object's elements. Meaning i have stored an username and a password in the object and i want to check it with another username and password which the user will provide at run time.
Here is what i have done :
//writing object to the file using printwriter
public void createLogin(String username,String password){
libraryLogin_class logins=new libraryLogin_class(username,password);
try{
PrintWriter write=new PrintWriter("login.txt");
write.print(logins);
write.close();
}catch(Exception e){}
}
//This method is not fully implemented am currently stuck at this method
public void checkLogin(String userName,String password)throws FileNotFoundException{
File read=new File("login.txt");
Scanner readFile=new Scanner(read);
String loginObject;
while(readFile.hasNext()){
loginObject=(readFile.nextLine());
//not implemented
}
//class which creates an object with the default username and password
public void login(){
String username="shehan";
String password="123";
createLogin_class user=new createLogin_class();
user.createLogin(username, password); //calls the creatLogin method and pass the parameters
}
So now my problem is how do i use the loginObject to check whether the object's username is equal to the username which the user provides?
Thank you for your time.
A PrintWriter
has a print(Object)
method as such
public void print(Object obj) {
write(String.valueOf(obj));
}
So calling
write.print(logins);
will write the value of logins.toString()
to your text file. You need to control that format. So if your toString()
method is
public String toString() {
return username + "," + password;
}
assuming you have fields username
and password
, you should read it as
while(readFile.hasNext()){
libraryLogin_class login = new libraryLogin_class();
loginObject = readFile.nextLine();
String[] values = loginObject.split(",");
login.setUsername(values[0]);
login.setPassword(values[1]);
// use login
}
You would obviously want to validate what you're reading first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.