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 12 of 12

Thread: loading things from a text file into an array list

  1. #1
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default loading things from a text file into an array list

    I'm trying to work out a way to save stuff in a text based game i'm making. The players inventory is an Array List. I worked out how to save the contents of it to a txt file but I have absolutely no idea about how to get that information back from the text file and reassign those values back to the array list. This is the code I've worked out.

    Load.java
    import java.util.*;
    import java.io.*;
     
    public class Load {
     
    	public void load() {
     
    		ArrayList<String> test = new ArrayList<String>();
     
    		try {
     
    			File file = new File("save.txt");
    			Scanner savedInv = new Scanner(file);
     
    			while (savedInv.hasNext()) {
     
    				String item = savedInv.nextLine();
    				test.add(item);
    				System.out.println(test);
     
    			}
     
    		}
     
    		catch (Exception e) {
     
    			System.out.println("Error loading file.");
     
    		}
     
    	}
     
    }

    Save.java
    import java.io.*;
    import java.lang.*;
    import java.util.*;
     
    public class Save {
     
    	public void save() {
     
    		player player = new player();
    		userInput input = new userInput();
     
    		input.getUserInput("Enter the item: ");
    		player.inventory.add(input.input);
    		input.getUserInput("Enter the item: ");
    		player.inventory.add(input.input);
    		input.getUserInput("Enter the item: ");
    		player.inventory.add(input.input);
     
    		try {
     
    		PrintWriter save = new PrintWriter(new FileWriter("save.txt"));
    		save.print(player.inventory + " ");
    		save.close();
     
    		}
     
    		catch (Exception e) {
     
    			System.out.println("error");
     
     
    		}
     
    	}
     
    }

    main.java
    public class main {
     
    	public static void main (String [] args) {
     
    		player player = new player();
    		Save save = new Save();
    		Load load = new Load();
    		userInput input = new userInput();
     
    		input.getUserInput("Save or Load?");
     
    		if (input.input.equals("save")) {
     
    			save.save();
     
    		}
     
    		if (input.input.equals("load")) {
     
    			load.load();
     
    		}
     
    	}
     
    }

    player.java
    import java.util.*;
     
    public class player {
     
    	ArrayList<String> inventory =  new ArrayList<String>();
     
    	public void add(String item) {
     
    		inventory.add(item);
     
    	}
     
    }

    The only problem is that when things are loading back in it takes the whole first line as one string making it one part of the array list when it should be 3 separate parts. any ideas?


  2. #2
    Junior Member
    Join Date
    Jan 2011
    Posts
    14
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Re: loading things from a text file into an array list

    Try using savedInv.next() instead of savedInv.nextLine()
    Last edited by dpek; January 23rd, 2011 at 08:02 PM. Reason: changed scan to savedInv to match problem

  3. #3
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: loading things from a text file into an array list

    I saved a,b,c in the text file which came to [a,b,c]. When I loaded it did this:

    Save or Load?
    load
    [[a,]
    [[a,, b,]
    [[a,, b,, c]]
    Press any key to continue . . .

  4. #4
    Junior Member
    Join Date
    Jan 2011
    Posts
    14
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Re: loading things from a text file into an array list

    However, in your save.java class, you are doing this:

    try {
    		PrintWriter save = new PrintWriter(new FileWriter("save.txt"));
    		save.print(player.inventory + " ");
    		save.close();
    }
    Which means your save data would look like: "a b c" instead of "a,b,c"

    Change your save data to "a b c" and use savedInv.next() instead of savedInv.nextLine(). This should fix your problem.

    Also, it would be a good idea to post an SSCCE; I cannot be 100% sure I'm telling you the correct way to do this, because you use a class called "userInput", and you do not provide information for this class.
    Last edited by dpek; January 23rd, 2011 at 08:34 PM. Reason: formatting

  5. #5
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: loading things from a text file into an array list

    This is the userInput class:

    import java.io.*;
     
    public class userInput {
     
    	String input = null;
     
    	public String getUserInput(String prompt) {
     
    		System.out.println(prompt + " ");
     
    		try {
     
    			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    			input = reader.readLine();
     
    			if (input.length() == 0)
    			return null;
     
    			return input;
     
    		} catch (IOException e) {
     
    			System.out.println("IOException: " + e);
     
    		}
     
    		return input;
    	}
     
    }

    Whenever I save the array list it will be the values in brackets with commas. I know I can change that after its saved but if i wanted to use this as a save format for a game it would be annoying for the user to change it. And yes that does fix the problem with the extra brackets and commas.

  6. #6
    Junior Member
    Join Date
    Jan 2011
    Posts
    14
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Re: loading things from a text file into an array list

    Quote Originally Posted by sp11k3t3ht3rd View Post
    I know I can change that after its saved but if i wanted to use this as a save format for a game it would be annoying for the user to change it. And yes that does fix the problem with the extra brackets and commas.
    I'm sorry, but I'm not quite sure what you're trying to say here.

    If you want to convert "a,b,c" to an array [a,b,c], so that the list of elements are put in the array correctly, the try block of your Load class should look something like this:

    try {
    	File file = new File("save.txt");
    	Scanner savedInv = new Scanner(file);
    	String[] elements = savedInv.nextLine().split(",");
    	for (String str : elements) {
    		test.add(str);
    		System.out.println(test);
    	}
    }

    Also, just a heads up, your save class saves the elements with the brackets. You will probably want to save it using the following method instead:

    try {
    	PrintWriter save = new PrintWriter(new FileWriter("save.txt"));
    	for(String str : player.inventory)
    		save.print(str + ",");
    	save.close();
    }

    ((See, SSCCEs really do help! :D))
    Last edited by dpek; January 23rd, 2011 at 08:47 PM.

  7. #7
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: loading things from a text file into an array list

    I meant that when I saved the array list to the file its format was [a,b,c]. I said that I knew you could take the brackets off after the file was saved (making the saved file look like "a,b,c") but it would be annoying for the user to half to go into their save file to take the brackets out. I changed my save try block you what you gave me and it saves without the brackets but it puts a comma after the c. Is there any way of preventing that? The deal with loading is that I need the values from the text file to be put back into the player inventory array list, not an the array of strings called element in the load try block you gave me.

  8. #8
    Junior Member
    Join Date
    Jan 2011
    Posts
    14
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Re: loading things from a text file into an array list

    Quote Originally Posted by sp11k3t3ht3rd View Post
    I meant that when I saved the array list to the file its format was [a,b,c]. I said that I knew you could take the brackets off after the file was saved (making the saved file look like "a,b,c") but it would be annoying for the user to half to go into their save file to take the brackets out. I changed my save try block you what you gave me and it saves without the brackets but it puts a comma after the c. Is there any way of preventing that?
    There is, but you don't need to, since the last comma is ignored when you load the file.

    Quote Originally Posted by sp11k3t3ht3rd View Post
    The deal with loading is that I need the values from the text file to be put back into the player inventory array list, not an the array of strings called element in the load try block you gave me.
    I'm guessing you've never seen foreach loops before and you don't know what .split() does.

    .split returns an array, which is why I instantiated the array elements. The string passed to split is just what character separates the items in the list.
    String[] elements = savedInv.nextLine().split(",");

    Then, I put all of the elements in the player inventory array list.
     for (String str : elements) {
         test.add(str);
         System.out.println(test);
     }

    I'm also assuming that test is the player inventory array list. If it isn't, then you're going to need to do this (I'm using the static solution I outlined from your other thread for this, meaning you have to make inventory in player.class static)
     for (String str : elements) {
         player.inventory.add(str);
         System.out.println(test);
     }

  9. The Following User Says Thank You to dpek For This Useful Post:

    sp11k3t3ht3rd (January 23rd, 2011)

  10. #9
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: loading things from a text file into an array list

    Thanks so much!

  11. #10
    Junior Member
    Join Date
    Jan 2011
    Posts
    14
    Thanks
    0
    Thanked 4 Times in 3 Posts

    Default Re: loading things from a text file into an array list

    Quote Originally Posted by sp11k3t3ht3rd View Post
    Thanks so much!
    Don't forget to mark this topic as solved by changing the topic title to "[SOLVED] loading things from a text file into an array list" ^____^

  12. #11
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: loading things from a text file into an array list

    Hey, I just was playing around with the program and it only loads 1 thing from the text file. If you have more than 1 thing in it, it doesn't get loaded. Any ideas? I changed the code to this:

    import java.util.*;
    import java.io.*;
     
    public class Load {
     
    	Player player = new Player();
    	mainMenu menu = new mainMenu();
     
    	public void load() {
     
    	try {
     
    		File file = new File("save.txt");
    		Scanner savedInv = new Scanner(file);
    		String[] elements = savedInv.nextLine().split(",");
     
    		for (String str : elements) {
     
    			if (Player.inventory.contains(str)) {
     
    				System.out.println("You've already loaded your file. You can't do this twice!");
    				break;
     
    			}
     
    			Player.inventory.add(str);
    			System.out.println("");
    			System.out.println("Your inventory is: " + Player.inventory);
    			System.out.println("");
    			menu.start();
     
    		}
     
    	}
     
    		catch (Exception e) {
     
    			System.out.println("Error loading file.");
    			menu.start();
     
    		}
     
    	}
     
    }

    because If you loaded more than once it kept adding the item to the inventory over and over again. The if statement isn't displayed when I load from a save with more than one item in it but it only loads the first item. So if my save looked like this: DP,BP,P. It would load DP and none of the others. But if I do it again it shows the You can't load twice thing and then it adds the second item.

    Save File for game interaction:
    BP,P,
    Example of game interaction:
    Welcome to the game!

    -------------------------
    | mine - Go to the mine |
    | shop - Go to the shop |
    | save - Save your game |
    | load - Load your game |
    -------------------------

    Enter your choice:
    load

    Your inventory is: [BP]

    Welcome to the game!

    -------------------------
    | mine - Go to the mine |
    | shop - Go to the shop |
    | save - Save your game |
    | load - Load your game |
    -------------------------

    Enter your choice:
    load
    You've already loaded your file. You can't do this twice!

    Your inventory is: [BP, P]

    Welcome to the game!

    -------------------------
    | mine - Go to the mine |
    | shop - Go to the shop |
    | save - Save your game |
    | load - Load your game |
    -------------------------

    Enter your choice:
    Last edited by sp11k3t3ht3rd; February 5th, 2011 at 10:46 AM.

  13. #12
    Member
    Join Date
    Oct 2010
    Posts
    38
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: loading things from a text file into an array list

    I added a line that prints out the array elements. And here's what it prints out:

    Welcome to the game!

    -------------------------
    | mine - Go to the mine |
    | shop - Go to the shop |
    | save - Save your game |
    | load - Load your game |
    -------------------------

    Enter your choice:
    load
    [Ljava.lang.String;@69b332
    Does anyone have any ideas because I got really confused by putting this debug statement in.

Similar Threads

  1. Loading array
    By joshft91 in forum Collections and Generics
    Replies: 3
    Last Post: January 19th, 2011, 10:30 AM
  2. Text File into String Array
    By mathanv in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 12th, 2010, 04:30 AM
  3. Reading lines of a text file into a string array
    By fortune2k in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 11th, 2010, 10:56 AM
  4. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM