Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.ArrayList;
- public class DataSavingTest {
- static int ObjectsSaved;
- public static void main(String[] args) {
- GameCharacter one = new GameCharacter(50, "Elf", new String[]{"bow", "sword", "dust"});
- GameCharacter two = new GameCharacter(200, "Troll", new String[]{"bare hands", "big ax"});
- GameCharacter three = new GameCharacter(120, "Magician", new String[]{"spells", "invisibility"});
- saveCharacterData(one, two, three); // testing
- ArrayList<GameCharacter> characterList = retrieveCharacterData(); // testing
- System.out.println(characterList.get(0).getType()); // testing
- System.out.println(characterList.get(1).getType()); // testing
- System.out.println(characterList.get(2).getType()); // testing
- }
- public static void saveCharacterData(Object... objects) {
- try {
- ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Save.txt"));
- for (Object o : objects) {
- os.writeObject(o);
- ObjectsSaved++;
- }
- os.close();
- } catch (FileNotFoundException ex) {
- ex.printStackTrace();
- System.out.println("Save file not found.");
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- public static ArrayList<GameCharacter> retrieveCharacterData() {
- ArrayList<GameCharacter> characterList = new ArrayList<>();
- try {
- ObjectInputStream is = new ObjectInputStream(new FileInputStream("Save.txt"));
- for (int i = 0; i < ObjectsSaved; i++) {
- GameCharacter character = (GameCharacter) is.readObject();
- characterList.add(character);
- }
- is.close();
- } catch (FileNotFoundException ex) {
- ex.printStackTrace();
- System.out.println("Save file not found.");
- } catch (ClassNotFoundException ex) {
- ex.printStackTrace();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- return characterList;
- }
- }
- _________________________________
- import java.io.*;
- public class GameCharacter implements Serializable {
- int power;
- String type;
- String[] weapons;
- public GameCharacter(int p, String t, String[] w) {
- power = p;
- type = t;
- weapons = w;
- }
- public int getPower() {
- return power;
- }
- public String getType() {
- return type;
- }
- public String getWeapons() {
- String weaponList = "";
- for (int i = 0; i < weapons.length; i++) {
- weaponList += weapons[i] + " ";
- }
- return weaponList;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement