简体   繁体   English

使用扫描仪从文件读取对象

[英]Using Scanner to read an object from a file

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? 所以现在我的问题是我如何使用loginObject来检查对象的用户名是否等于用户提供的用户名?

Thank you for your time. 感谢您的时间。

A PrintWriter has a print(Object) method as such PrintWriter具有这样的print(Object)方法

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. 会将logins.toString()的值写入文本文件。 You need to control that format. 您需要控制该格式。 So if your toString() method is 因此,如果您的toString()方法是

public String toString() {
    return username + "," + password;
}

assuming you have fields username and password , you should read it as 假设您有用usernamepassword字段,则应阅读为

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. 您显然希望先验证您正在阅读的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM