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?