I am working on a bukkit plugin. One thing I want this plugin to do is teleport you to other worlds on the server. However, I don't want the player's inventory to be saved.

Right now, I have this code:

File playerInvConfigFile = new File(plugin.getDataFolder() + File.separator + "players" + File.separator + sender.getName(), "inventory.yml");
FileConfiguration pInv = YamlConfiguration.loadConfiguration(playerInvConfigFile);

        Player user = (Player)sender;
        PlayerInventory inv = user.getInventory();

        String worldName = user.getWorld().getName();
        int i = 0;
        for (ItemStack stack : inv.getContents()){
            String start = worldName + "." + Integer.toString(i);

            pInv.set(start + ".amount", stack.getAmount());
            pInv.set(start + ".durability", stack.getDurability());
            pInv.set(start + ".type", stack.getTypeId());

This works great, but there is a big problem: enchantments are now saved! This is a big problem. I want to know how to both save enchantments to a file, and then read them back in and set them!

Thank you all!


1 Answer 1


There are two methods on ItemStack that you will find of use:

The first is getEnchantments, which returns a Map, which you will need to use an iterator to go through and save off the keys and values.

Map<Enchantment,Integer> enchantments = itemStack.getEnchantments();
Iterator<Entry<Enchantment,Integer>> iter = enchantments.entrySet().iterator();
    Entry<Enchantment,Integer> entry = iter.next();
    //do something with the entry

When you restore the inventory, you need to create a new HashMap, restore the values within the original map, and restore them to the ItemStack, using addEnchantments, which takes as its sole parameter a Map, so you deserialize whatever you serialized before, and then add it to the ItemStack like so:

  • \$\begingroup\$ thank you very much, but one thing that troubles me is do i just call all of them from the file i am saving them to? and then do the addEnchantments? \$\endgroup\$
    – HcgRandon
    Mar 14, 2012 at 12:50
  • \$\begingroup\$ After saving them off to file, when you load them in, there is an Enchantment.getByName function, and an Integer.parseInt (or Integer.decode if you prever) function to bring them back into memory, and then use the Map's "put" function to load up the Map. \$\endgroup\$ Mar 14, 2012 at 13:52
  • \$\begingroup\$ I'm facing the same problem right now. The concept is clear, but the HashMap is not working. Do you have any example code? I would really appreciate it! Thanks! \$\endgroup\$ May 16, 2012 at 13:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .