Some Background:
I'm making an RPG text based game for class, and I'm using an ArrayList
for the inventory, since of course, it will constantly be changing whenever another item is added. I want to be able to save this ArrayList
into a txt file and I want to be able to load it back into the same ArrayList
so the player can pick up where they left off.
I'm using FileReader
and FileWriter
, and BufferedReader
and BufferedWriter
currently. This is because someone else in the class made the save method for me, so I don't really know how to change it to something else if I wanted. Can I do what I'm trying to do with BufferedWriter
? I don't really know what kind of code I should put on here, but this is how I declared the ArrayList if that helps:
ArrayList<String> bagWeapons = new ArrayList<String>();
And my save method is:
void save(){
try {
FileWriter fileWriter =
new FileWriter(fileName);`
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
//EDIT ZONE
bufferedWriter.write(name); //playerName
bufferedWriter.newLine();
String hpSave = String.valueOf(hp1); //tempHP conversion
bufferedWriter.write(hpSave); //playertempHP
bufferedWriter.newLine();
String fullhpSave = String.valueOf(fullHP);
bufferedWriter.write(fullhpSave); //playerfullHP
bufferedWriter.newLine();
for(int i=0; i<bagWeapons.size(); i++)
bufferedWriter.write(bagWeapons.get(i) + ","); //player weapon inventory
//END EDIT ZONE
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
}
}
Does the "for" loop work like that? The print on the text file is: WeaponName,WeaponName,WeaponName, ....
I have no idea what I would do to write the ArrayList back. I've tried stuff but my program blows up every time.
The for loop work like this.To read the data back, you could read the whole string example: weapon1,item2,item99 into a String object and then split the String with a delimiter "," using split function of string class and then build the new array.example.
String text="weapon1,item2,item99";
String parts[]=text.split(",");
for(int i=0;i<parts.length();i++)
Inventory.add.parts[i] // or however you set it up.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.