0

I'm trying to store user account information into a separate text file, which I have accomplished after many attempts...

However each time I create a new user it overwrites the last one put into the file. Also, the only thing that is being stored is Strings, I have a PIN number and an account balance that I will need for later that are very important.

Here is was I have so far, I believe that the problem is that each time I run the code an Object named user is being created, and since it's not dynamic it just overwrites itself every time.

I am a noob when it comes to serializing anything so if you could explain the problem in the simplest terms that would be awesome!

The goal is for me to be able to store each new users account, and then come back at a later point to display them to a user if the account information matches the pin number and username

public class ATM implements Serializable {

public static void main(String[] args) {

    // variables
    String dash = "-------------------\n";
    int accounts = 0;

    // Scanner
    Scanner scanner = new Scanner(System.in);

    // Welcome screen
    System.out.print(dash);
    System.out.print("Welcome to the Bank\n");
    System.out.print(dash);

    System.out.println("Do you have an account with us? (y/n) ");

    String answer = scanner.nextLine();

    if (answer.equalsIgnoreCase("y")) {

    } else {

        // new user is created
        Bank bank = new Bank();

        accounts++;

        System.out
                .println("Enter your full name below (e.g. John M. Smith): ");
        String name = scanner.nextLine();
        System.out.println("Create a username: ");
        String userName = scanner.nextLine();
        System.out.println("Enter your starting deposit amount: ");
        int balance = scanner.nextInt();

        System.out.print(dash);
        System.out.print("Generating your information...\n");
        System.out.print(dash);

        int pin = bank.PIN();
        String accountNum = bank.accountNum();

        String id = name + accountNum;

        User user = new User(name, userName, pin, accountNum, balance);

        // new user gets added to the array list
        Bank.users.add(user);

        String test = "Test989898998";

        System.out.println(user);

        try {
            FileOutputStream fileOut = new FileOutputStream("users.txt");

            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            out.writeObject(Bank.users);
            out.close();
            fileOut.close();

        } catch (IOException i) {
            i.printStackTrace();
        }
    }

}

}

Bank Class

public class Bank implements Serializable {

//Generate a random 16 digit bank account number
public String accountNum() {

    int max = 9999;
    int min = 1000;

    int a1 = (int) (Math.random() * (max - min) + min);
    int a2 = (int) (Math.random() * (max - min) + min);
    int a3 = (int) (Math.random() * (max - min) + min);
    int a4 = (int) (Math.random() * (max - min) + min);

    String accountNum = a1 + "-" + a2 + "-" + a3 + "-" + a4;

    return accountNum;
}

//Generate a random 4 digit PIN
public int PIN() {

    int max = 9999;
    int min = 1000;

    int PIN = (int) (Math.random() * (max - min) + min);

    return PIN;
}

//array list for users
static ArrayList<User> users = new ArrayList<User>() {

};

}

User Class

public class User implements Serializable{

String name;
String userName;
String accountNum;
int pin;
int balance;

public User (String name, String userName, int pin, String accountNum, int balance) {

    this.name = name;
    this.userName = userName;
    this.accountNum = accountNum;
    this.pin = pin;
    this.balance = balance;
}

public String toString() {

    return "Name: " + this.name + "\n\nUsername: " + this.userName + " | " + "Pin: " + this.pin + "\n\n"
             + "Account Number: " + this.accountNum + "\n\nAccount Balance: $" + this.balance + 
            "\n\nNever share your login information with anyone!";
}

}
23k
  • 1,596
  • 3
  • 23
  • 52
  • Post you `User` and `Bank` classes. – PM 77-1 Jan 15 '14 at 01:20
  • @PM77-1 I put them up there for ya – 23k Jan 15 '14 at 01:41
  • I see. Your constructor for `User` class seems to be OK. PIN and account number should've been assigned and saved as part of a `User` object. Are you 100% sure they are not? – PM 77-1 Jan 15 '14 at 01:45
  • When your program starts does it read in the users object from the saved object instance? I don't see that in the code you posted so it would constantly overwrite the file with only the new user. Long winded... but keep in mind that when Java compiles an object it creates a serial version variable that it compares when you write out the object and try to read it back in. If in one compile/run you save and then make changes to the User object you won't be able to read it back in (Exception). – JavaCoderEx Jan 15 '14 at 02:16
  • @JavaCoderEx when I read the code from the text file, I don't see any numbers that would represent a PIN or a User Balance. The only numbers I see are the bank account numbers, which is technically a string since it has the dashes in between... Regardless of if I solve this problem of stuff being written over, the program is useless without the ability to read a PIN number and Balance from a users account. – 23k Jan 15 '14 at 02:48
  • @JavaCoderEx Is serialization the best option for what I'm trying to do? I'm still a beginning programmer, so I don't want to get to complex with this project. – 23k Jan 15 '14 at 02:50
  • @JavaCoderEx and I don't think I'm reading the users object code from the saved object instance, could you show me how to do that? – 23k Jan 15 '14 at 03:00
  • Checkout this: http://stackoverflow.com/questions/6484428/java-read-object-input-stream-into-arraylist – JavaCoderEx Jan 15 '14 at 03:14
  • Btw, note that Serializable does not mean human-readable in a text editor - so I'm not surprised you don't see them in the file since they're binary data, so they're written out as binary regardless of whether your file name has a ".txt" extension – racraman Jan 15 '14 at 03:35

1 Answers1

1

However each time I create a new user it overwrites the last one put into the file.

That's correct. You're not appending to the file, you're creating a new one. This has nothing to do with objects or serialization, it is just a matter of which constructor for FileOutputStream you are using.

However, without using a trick which I won't reference here, you can't append to object streams, because there is a header which will confuse subsequent readers. You would need to read in the entire file and write it out again. The simplest way to do this is to serialize an ArrayList<User> instead of the User object itself.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Still confused, think you could explain it in simpler terms for me? – 23k Jan 15 '14 at 14:55
  • What part of 'serialize an ArrayList' don't you understand? – user207421 Jan 15 '14 at 20:18
  • I thought that In the above code, I created a new person object, added it to the `ArrayList`. And then serialized the list by writing `out.writeObject(Bank.users)` – 23k Jan 15 '14 at 22:08
  • Did you read the old `ArrayList` from the file before you did that, or just start with an empty one? – user207421 Jan 16 '14 at 10:11