Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: How to save/access class objects on a .txt file?

  1. #1
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default How to save/access class objects on a .txt file?

    Hello, I'm working on a 2-Step authentication program, that currently stores a user's account info such as username, password, and twoStepChoice within an 'Account' object, and each of those objects is stored within an ArrayList of type 'Account' and my question is, before ending the program, how can I save those 'Account' objects onto a .txt file, of course, with their respective account details still linked, onto a .txt file, and when restarting the program, how can I read in the objects with their respective details?

    My Code Below (Excuse my comments, they're just for recalling what each method does):

    Note: If you run the code, I do output the account details, which security-wise you don't want to do of course, but this is just to see that everything is working and being saved properly. Additionally, any advice, words of improvement, or positive criticism is very much welcomed.

    The class that deals with the functions of the program:
    package LoginProject;
     
    import java.util.ArrayList;
    import java.util.Scanner;
     
    public class LoginFunctions {
     
    	//	ArrayList to hold 'Account' objects, Scanner for input, 'option' for methods, 'twoStep' for checking whether to execute 2-Step Authentication or not
    	private static ArrayList<Account> myAccount = new ArrayList<Account>();
    	private static Scanner sc = new Scanner(System.in);
    	private static int option;
    	private static boolean twoStep;
     
    	//	Used to display Account info
    	public static void displayAccount() {
    		for(int i=0; i<myAccount.size(); i++) {
    			System.out.println("\nUsername: " + myAccount.get(i).getUsername());
    			System.out.println("Password: " + myAccount.get(i).getPassword());
    			System.out.println("2-Step Authentication Choice: " + myAccount.get(i).isTwoStepChoice());
    		}
    	}
     
    	//	Used to check if there exists an account with the String 'username' passed
    	private static int findAccount(String username) {
    		for(int i=0; i<myAccount.size(); i++) {
    			if(myAccount.get(i).getUsername().equals(username))
    				return i;
    		}
    		return -1;
    	}
     
    	//	Used to add/create a new Account
    	private static void addAccount(String username, String password, boolean twoStepChoice) {
    		if(findAccount(username) == -1) {
    			myAccount.add(new Account(username, password, twoStepChoice));
    		} else {
    			System.out.println("Username already taken.");
    		}
    	}
     
    	//	Used to print the options at the start of the program
    	public static void printOptions() {
    		boolean valid = false;
     
    		while(!valid) {
    			System.out.print("If you're a new user, enter 1, else, enter 2: ");
    			valid = validate();
    			sc.nextLine();
    		}
    		newOrOldUser();
    	}
     
    	//	Used to either create the new Account, or execute the 2-Step Authentication/proceed with the program
    	private static void newOrOldUser() {
     
    		String username, password;
    		boolean valid = false;
     
    		switch(option) {
    		case 1:
    			System.out.print("\nEnter your Username: ");
    			username = sc.nextLine();
    			System.out.print("\nEnter your desired password: ");
    			password = sc.nextLine();
     
    			//	Prompts user if they would like to activate 2-Step or not, with validation
    			while(!valid) {
    				System.out.print("\nIf you would like to use 2-Step Authentication, enter 1, otherwise, enter 2: ");
    				valid = validate();
    				sc.nextLine();
    			}
    			if(option == 1)
    				twoStep = true;
    			else
    				twoStep = false;
    			addAccount(username, password, twoStep);
    			break;
    		case 2:
    			System.out.println("\nWelcome back.");
    			break;
    		}
    	}
     
    	//	Used to validate the given input at the start of the program (new or existing user)
    	private static boolean validate() {
     
    		boolean valid = false;;
     
    		if(sc.hasNextInt()) {
    			option = sc.nextInt();
    			if(option == 1 || option == 2) {
    				valid = true;
    			} else {
    				System.out.println("Invalid number. Please try again.\n");
    			}
    		} else {
    			System.out.println("Invalid option. Please try again.\n");
    			sc.next();
    		}
    		return valid;
    	}
     
    	private static void saveAccount() {
     
    	}
     
    }//end LoginFunctions

    Account Class:
    package LoginProject;
     
    public class Account {
     
    	private String username;
    	private String password;
    	private boolean twoStepChoice;
     
    	public Account(String username, String password, boolean twoStepChoice) {
    		this.username = username;
    		this.password = password;
    		this.twoStepChoice = twoStepChoice;
    	}
     
    	public String getUsername() {
    		return username;
    	}
     
    	public String getPassword() {
    		return password;
    	}
     
    	public boolean isTwoStepChoice() {
    		return twoStepChoice;
    	}
     
    	//To create new 'Account' objects
    	public static Account createAccount(String username, String password, boolean twoStepChoice) {
    		return new Account(username, password, twoStepChoice);
    	}
     
    }//end Accounts

    The Main Class:
    package LoginProject;
     
    import java.util.Scanner;
     
    public class TwoStepVerification {
     
    	private static Scanner sc = new Scanner(System.in);
    	private static LoginFunctions lf = new LoginFunctions();
     
    	public static void main(String[] args) {
     
    		System.out.print("Welcome to Blank Program!\n\n");
    		lf.printOptions();
    		lf.displayAccount();
     
    		System.out.println("\nProgram ran successfully!");
     
    	}//end MAIN
     
    }//end CLASS
    Last edited by HyperRei; August 28th, 2021 at 07:56 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,530
    Thanks
    55
    Thanked 2,659 Times in 2,609 Posts

    Default Re: How to save/access class objects on a .txt file?

    how can I save those 'Account' objects onto a .txt file
    Define a layout for each record (corresponds to an Account object) and use that to define what bytes of each data field are stored where.
    If the fields are variable length, that will make the solution just a little harder.
    If the fields are all fixed length, then the program should be straight forward.

    For example if there is a String field and a number field, the field lengths could be 20 characters for the String and 6 for the number:
    Name: John Smith
    Age: 34
    The record would be 20+6 characters long with the name in the first 20 characters and the number (in a String) in the next 6
    John Smithbbbbbbbbbb000034
    Where I have shown blanks as b

    Another approach but it is not a .txt file would be to serialize the class.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: How to save/access class objects on a .txt file?

    I'm having a bit of trouble understanding. So, I should save the data onto a file where the entry is of fixed length as you've said, so the file would look something like this (limiting to lenght 26 of course):

    Username,Password,TwoStepChoice // <-- header
    username1,password1,true
    username2,password2,false
    username3,password3,false

    Then read in the data to its appropriate spot? As in, the first line, I'd use the split(",") method, throw it into an array, then add the respective details into each record?

    I'd have an array of usernames, an array of passwords, and another for the TwoStepChoice, then run it through a loop, and add the respective details right? Or did you mean something else, perhaps simpler?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,530
    Thanks
    55
    Thanked 2,659 Times in 2,609 Posts

    Default Re: How to save/access class objects on a .txt file?

    Sorry, I forgot to mention separating the fields in a record with a special character and then using split to separate the fields.
    But I see that you have thought of it. That should work for you.

    You would not use arrays to store the data. After using split that creates an array, pick each element out of the array and use it in the constructor for the Account class. Or pass the array to the constructor; Or pass the unparsed line to the constructor and do the split there and extract the data to the appropriate variables in the Account class.
    If you don't understand my answer, don't ignore it, ask a question.

  5. The Following User Says Thank You to Norm For This Useful Post:

    HyperRei (August 28th, 2021)

  6. #5
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: How to save/access class objects on a .txt file?

    Alright, just tried it and it seems to be running properly. Thank you.

Similar Threads

  1. Replies: 6
    Last Post: March 16th, 2014, 08:03 PM
  2. Replies: 7
    Last Post: March 10th, 2014, 04:28 PM
  3. Replies: 1
    Last Post: July 26th, 2013, 03:25 AM
  4. how to access array f objects in java
    By Fanta Hubert in forum What's Wrong With My Code?
    Replies: 18
    Last Post: May 27th, 2013, 09:36 PM
  5. Replies: 5
    Last Post: March 2nd, 2012, 11:34 AM

Tags for this Thread