Samuel W
Samuel W

Reputation: 39

How to use ObjectInputStream to find a class instance in a list of instances

I am trying to create an instance of the class Account and it cannot have the same handle as other accounts, which is checked using a for loop which compares the handle passed a parameter to the handles of the existing accounts, if it already exists then the exception IllegalHandleException is thrown

How do you go from having the read file to the list of the accounts, i.e. what needs to replace //listOfaccounts=list of each account before the for loop

public int createAccount(String handle) throws IllegalHandleException{
    //checks if handle is already taken
    FileInputStream accountsFile=new FileInputStream("listOfAccounts.txt");
    ObjectInputStream in=new ObjectInputStream(accountsFile);

    //listOfAccounts=list of each account 

    for (Account accounts : listOfAccounts){
        if (handle==accounts.getHandle()){
            throw new IllegalHandleException("Handle Is Already Taken");
        }
    }

    //create account
    Account newAccount;
    newAccount=new Account(handle);

    //add account to the stream
    FileOutputStream updatedAccountsFile=new FileOutputStream("listOfAccounts.txt");
    updatedAccountsFile.write(newAccount.getUserID());
    ObjectOutputStream out=new ObjectOutputStream(updatedAccountsFile);

    //return ID 
    return newAccount.getUserID();
}

Upvotes: 0

Views: 42

Answers (0)

Related Questions