File Reading and Writing for Object Array Lists

Viewed 44

Currently trying to write a Account Directory using a Array List to store an account object without dependencies and such. Having trouble saving the array list of objects to a file. I need help me with reading/writing to file to make each object readable even after saving to a file.

static ArrayList<Account> accounts = new ArrayList<>();

public AccountRead() {
    try {
        FileInputStream f = new FileInputStream(new File("AccountDirectory.txt"));
        ObjectInputStream o = new ObjectInputStream(f);

        // Read objects
        accounts = (ArrayList<Account>) o.readObject();

        o.close();
        f.close();

        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            System.out.println("Error initializing stream");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        
    }
    SetAccounts();

}

public static ArrayList<Account> SetAccounts() {
    return accounts;
}

Obviously theres not really much encryption or safegaurds for the data as its a personal project but this is the most recent way I have tried

static ArrayList<Account> accounts = new ArrayList<>();

public AccountWrite() {
    accounts = Account.SetAccounts();
    try{
        FileOutputStream f = new FileOutputStream(new File("AccountDirectory.txt"));
        ObjectOutputStream o = new ObjectOutputStream(f);
    
        o.writeObject(accounts);
        o.flush();
        o.close();
    
    }catch (IOException e) {
        e.printStackTrace();
    }
    accounts.clear();

}

If there are any other ways of saving this information or ways to save an object using an identifying characteristic such as ID numbers that will be great. The following is my code for the account

public Account(int ID, String username, char[] passwordChar, User user, String firstName, String displayName, String phonenumber,
        String email, String country, String state) {
    this.AccountID = ID;
    this.username = username;
    this.password = passwordChar.toString();
    this.user = user;
    this.firstName = firstName;
    this.displayName = displayName;
    this.phonenumber = phonenumber;
    this.email = email;
    this.country = country;
    this.state = state;
    PrintAccount();
    accounts = RegisterGUI2.SetAccounts();
    accounts = Setup.SetAccounts();
    SetAccounts();
    new AccountWrite();
}    

public static ArrayList<Account> SetAccounts() {
    return accounts;
}
0 Answers
Related