Solved Save / Load HashMap to file (Inventory)

Discussion in 'Plugin Development' started by Hester, Nov 11, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    Hester

    SOLVED: http://forums.bukkit.org/threads/serialize-inventory-to-single-string-and-vice-versa.92094/

    Hey i have some problem with save and load inventory to file
    1. what type of file it needs to be
    2. I use this http://wiki.bukkit.org/Plugin_Tutorial#Saving.2FLoading_a_HashMap but i have some problem how i can load inventory on this file ?

    I wrote a function to save items but I'm not sure if it is good
    Code:
    public void saveInventory(Player player) {
            this.mySavedItems.put(player.getName(), copyInventory(player.getInventory()));
     
            File inventoryFile = new File("plugins\\Plugin\\inv", player.getName().toLowerCase() + ".bin <<< ? ");
            if (!inventoryFile.exists()) {
                  try {
                    inventoryFile.createNewFile();
                } catch (Exception e) {
                      e.printStackTrace();
                }
            }
     
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("plugins\\Plugin\\inv\\" + player.getName().toLowerCase() + ".bin <<< ?"));
                oos.writeObject(this.mySavedItems.put(player.getName().toLowerCase(), copyInventory(player.getInventory())));
                oos.flush();
                oos.close();
            } catch(Exception e) { e.printStackTrace(); }
     
        }
    and now how i can load this to HashMap and give back items for player ?
     
  2. Offline

    bryce325

    Instead of an outstream use and instream loading from the the location it is saved to with a
    Code:
                        BufferedReader inStream = new BufferedReader(new FileReader(chunkFile));
    Is what I do usually
    I also usually use a buffered writer to put stuff to file so I don't know if that would work with yours.
     
  3. Offline

    fireblast709

  4. Offline

    Hester

    what is the best file type to save hashmap ?
     
  5. Offline

    TwistedMexi

    Any really in this case, but I suppose "officially" it's preferable to use yaml, and use the methods in the link fireblast provided for loading/saving.
     
  6. Offline

    Hester

    hey again :D i have next question :D
    Code:
            configFile = new File("\\plugins\\PLUGIN\\inv", player.getName().toLowerCase() + ".yml");
            uconf = new YamlConfiguration();
    i have opened the file, when I stopped using SAVEFILE function the file is still open? if so, how to turn it off (close)
     
  7. Offline

    fireblast709

    now load the file
    Code:java
    1. uconf.loadConfiguration(configFile);

    Then you can use it like I said before. To save it, call the following:
    Code:java
    1. uconf.save(File f);

    And you do not have to save in between, only if you want to backup and such, and obviously in onDisable()
     
  8. Offline

    Hester


    i have
    Code:
        public void saveInventory(Player player) {
            this.mySavedItems.put(player.getName(), copyInventory(player.getInventory()));
     
            configFile = new File("\\plugins\\PLUGIN\\inv", player.getName().toLowerCase() + ".yml");
            uconf = new YamlConfiguration();
     
            if(!configFile.exists()) {
                configFile.getParentFile().mkdirs();
                try {
                    configFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
         
            ItemStack[] savedInventory = this.mySavedItems.get(player.getName());
            uconf.set(player.getName().toLowerCase(), savedInventory);
            uconf.getDefaults().options().copyDefaults(true);
            try {
                uconf.save(configFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
         
            this.mySavedItems.remove(player.getName());
          AND HERE I CAN CLOSE THIS LOADED FILE ? OR WHEN I STOP USING THIS FUNCTION THE FILE WILL CLOSED ?
        }
    this code at the top is good? or something is missing?
    and next question(last) when i have saved ItemStack[] array how i can load this :D ? i try

    Code:
            ItemStack[] inventory = uconf.getItemStack[](player.getName().toLowerCase());
            player.getInventory().setContents(inventory);
    but i have error "Type mismatch: cannot convert from ItemStack to ItemStack[]" ? What can i do ?
     
  9. Offline

    fireblast709

    you load in a single ItemStack, this is not the same as an ItemStack array.
    you probably have to load in the ItemStacks in the config as a list and load them as:
    Code:java
    1. ItemStack[] inventory = ((ArrayList<ItemStack>)inv.getList(player.getName().toLowerCase(), new ArrayList<ItemStack>().toArray())).toArray(new ItemStack[0]);
    2.  
     
  10. Offline

    Hester

    ok, now i can save item but i have problem with loading :D
    when i try get ItemStack array i have error
    Code:
            ItemStack[] inventory = ((ArrayList<ItemStack>)uconf.getList(player.getName().toLowerCase(), new ArrayList<ItemStack>().toArray())).toArray(new ItemStack[0]);       
    
    " The method getList(String, List<?>) in the type MemorySection is not applicable for the arguments (String, Object[]) "

    Maybe its easy :D but I was looking at other sites but no results: (
     
  11. Offline

    fireblast709

    typing too fast, sorry
    Code:java
    1. ItemStack[] inventory = ((ArrayList<ItemStack>)uconf.getList(player.getName().toLowerCase(), new ArrayList<ItemStack>())).toArray(new ItemStack[0]);

    errors happen when you write code too fast and move around with stuff
     
  12. Offline

    Hester

    Eh.. i don't know what i do wrong :( but i must add @SuppressWarnings("unchecked") to this above code. I tried everything but when i try restore items it only returned air(nothing)

    Code:
    @SuppressWarnings("unchecked")
    ItemStack[] inventory = ((ArrayList<ItemStack>)uconf.getList(player.getName().toLowerCase() + ".items", new ArrayList<ItemStack>())).toArray(new ItemStack[0]);
    player.getInventory().setContents(inventory);
     
  13. Offline

    fireblast709

    are they saved properly? (like after saving, check the config)
     
  14. Offline

    Hester

    Yes, this is saved hesterq.yml file
    Code:
    hesterq:
      exp: 0.8235292
      health: 20
      items: !!org.bukkit.craftbukkit.inventory.CraftInventoryPlayer
        armorContents:
        - ==: org.bukkit.inventory.ItemStack
          type: LEATHER_BOOTS
        - ==: org.bukkit.inventory.ItemStack
          type: CHAINMAIL_LEGGINGS
        - ==: org.bukkit.inventory.ItemStack
          type: DIAMOND_CHESTPLATE
        - ==: org.bukkit.inventory.ItemStack
          type: IRON_HELMET
        boots:
          ==: org.bukkit.inventory.ItemStack
          type: LEATHER_BOOTS
        chestplate:
          ==: org.bukkit.inventory.ItemStack
          type: DIAMOND_CHESTPLATE
        contents:
        - ==: org.bukkit.inventory.ItemStack
          type: SLIME_BALL
          amount: 13
        - ==: org.bukkit.inventory.ItemStack
          type: GRASS
        - ==: org.bukkit.inventory.ItemStack
          type: WOOD_SWORD
        - ==: org.bukkit.inventory.ItemStack
          type: DIRT
          amount: 9
        - ==: org.bukkit.inventory.ItemStack
          type: ARROW
        - null
        - null
        - null
        - ==: org.bukkit.inventory.ItemStack
          type: STRING
          amount: 3
        - ==: org.bukkit.inventory.ItemStack
          type: NOTE_BLOCK
        - ==: org.bukkit.inventory.ItemStack
          type: NOTE_BLOCK
        - null
        - ==: org.bukkit.inventory.ItemStack
          type: NOTE_BLOCK
        - ==: org.bukkit.inventory.ItemStack
          type: NOTE_BLOCK
        - ==: org.bukkit.inventory.ItemStack
          type: SEEDS
        - ==: org.bukkit.inventory.ItemStack
          type: NOTE_BLOCK
          amount: 59
        - ==: org.bukkit.inventory.ItemStack
          type: NOTE_BLOCK
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        - null
        helmet:
          ==: org.bukkit.inventory.ItemStack
          type: IRON_HELMET
        itemInHand:
          ==: org.bukkit.inventory.ItemStack
          type: GRASS
        leggings:
          ==: org.bukkit.inventory.ItemStack
          type: CHAINMAIL_LEGGINGS
        maxStackSize: 64
    Or is the ability to download it through the loops, or something else?
     
  15. Offline

    fireblast709

    How do you save this?
     
  16. Offline

    Hester

    Code:
        //INVENTORY   
        public void saveInventory(Player player,String world) {   
            configFile = new File("plugins\\PLUGIN\\inv", player.getName().toLowerCase() + ".yml");
            uconf = new YamlConfiguration(); 
                 
            if (!configFile.exists()) {
                  try {
                    configFile.createNewFile();
                } catch (Exception e) {
                      e.printStackTrace();
                }           
                  try {
                      uconf.save(configFile);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
            }
           
            uconf.set(player.getName().toLowerCase() + ".exp", player.getExp());
            uconf.set(player.getName().toLowerCase() + ".health", player.getHealth());
            uconf.set(player.getName().toLowerCase() + ".items", player.getInventory());
            try {
                uconf.save(configFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
                   
        }
             
        public void restoreInventory(Player player,String world){
            configFile = new File("plugins\\PLUGIN\\inv", player.getName().toLowerCase() + ".yml");
            uconf = new YamlConfiguration(); 
           
            @SuppressWarnings("unchecked")
            ItemStack[] inventory = ((ArrayList<ItemStack>)uconf.getList(player.getName().toLowerCase() + ".items", new ArrayList<ItemStack>())).toArray(new ItemStack[0]);
            player.getInventory().setContents(inventory);
        }
     
  17. Offline

    fireblast709

    is... it even possible to save it like this?
     
  18. Offline

    one4me

    Hester
    You could try InventoryIO, a class I made specifically to save inventories.
    You would call the methods like this:
    Code:
    /*returns true if successfully saved or false otherwise*/
    boolean saved = InventoryIO.savePlayerInventoryTo("PlayerName", new java.io.File(getDataFolder(), "FileName"));
     
    /*returns a new instance of org.bukkit.inventory.PlayerInventory or null if there was an error*/
    org.bukkit.inventory.PlayerInventory inv = InventoryIO.loadPlayerInventoryFrom(new java.io.File(getDataFolder(), "FileName"));
    
    and it will produce a file that would have a setup similar to this:
    Code:
    Inventory:
      '0':
        id: 261
        Damage: 0
        Count: 1
        tag:
          ench:
            '0':
              id: 48
              lvl: 3
      '1':
        id: 262
        Damage: 0
        Count: 64
      '2':
        id: 269
        Damage: 13
        Count: 1
      '3':
        id: 7
        Damage: 0
        Count: 3
      '4':
        id: 145
        Damage: 0
        Count: 1
      '5':
        id: 384
        Damage: 0
        Count: 1
      '6':
        id: 283
        Damage: 0
        Count: 1
        tag:
          ench:
            '0':
              id: 20
              lvl: 1
          display:
            Name: My Gold Sword it's Enchanted
          RepairCost: 2
      '8':
        id: 1
        Damage: 0
        Count: 64
        tag:
          ench:
            '0':
              id: 16
              lvl: 5
            '1':
              id: 33
              lvl: 1
          display:
            Name: §r§kMagic Stone
            lore:
              '0': §dMagicl Stone
      '15':
        id: 387
        Damage: 0
        Count: 1
        tag:
          title: TestBooklet
          author: Player
          pages:
            '0': 'test book
    
              1
    
              2
    
              3
    
              4
    
              5
    
              '
            '1': 'page 2
    
              2
    
              3
    
              4
    
              5
    
              6'
            '2': 'page 3
    
              test
    
              test'
      '19':
        id: 388
        Damage: 0
        Count: 64
      '21':
        id: 19
        Damage: 0
        Count: 1
      '29':
        id: 351
        Damage: 13
        Count: 6
      '32':
        id: 20
        Damage: 0
        Count: 1
      '34':
        id: 12
        Damage: 0
        Count: 3
      '102':
        id: 311
        Damage: 0
        Count: 1
        tag:
          ench:
            '0':
              id: 0
              lvl: 3
      '103':
        id: 298
        Damage: 0
        Count: 1
    
    
    
    The inventory is saved this way so that it can easily be edited, but if you have no need for that, you could easily save the inventory using some methods designed to save NBT data found in the Craftbukkit jar.
     
  19. Offline

    Hester

Thread Status:
Not open for further replies.

Share This Page