Writing bukkit objects to file using ObjectOutputStream

Discussion in 'Plugin Development' started by Megalegomand, May 24, 2013.

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

    Megalegomand

    I'm working on a plugin were i need to write a inventory object to a file but i think bukkit has a problem with there objects so you can't write them directly to files using ObjectOutputStream

    Code to write it to the file:

    Code:
    public void saveObject(Object obj, String file) {
     
            try {
                FileOutputStream fileOutput = new FileOutputStream(file);
                ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
                objectOutput.writeObject(obj);
                objectOutput.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    I really hope some of you can help me :D
     
  2. Offline

    catageek

    No one can help you on a hypothetic problem. What is exactly the error or unexpected behaviour you get when executing this code ?
     
  3. Offline

    ShadowDog007

    Megalegomand
    You can only save objects to a file if they implement Serializable (Same goes for fields inside the object your saving). I don't think any of the bukkit objects do.

    You will have to save the data in your own object, and then write it to a file. And convert it back to a normal inventory after reading.
     
  4. Offline

    Seadragon91

    You could take a look on my ItemParser class.

    Example:
    Code:
    // save inventory
    YamlConfiguration yaml = new YamlConfiguration();
    yaml.set("inventory", ItemParser.getHashMapFromItemStackArray(player.getInventory().getContents()));
    yaml.set("armor", ItemParser.getHashMapFromItemStackArray(player.getInventory().getArmorContents()));
     
    // load inventory
    YamlConfiguration yaml = new YamlConfiguration();
    ItemStack[] inventory = ItemParser.getItemStackArrayFromHashMap(yaml.getConfigurationSection("inventory"), 36);
    ItemStack[] armor = ItemParser.getItemStackArrayFromHashMap(yaml.getConfigurationSection("armor"), 4);
    player.getInventory().setContents(inventory);
    player.getInventory().setArmorContents(armor);
    You can then save the yaml into a file, I would save inventory into a own file and compress it over GZIPOutputStream, because the file can be big and if you compress it, they will be then very small.
    How to compress a file and loading it, google it.

    If you have any questions ask.
     
Thread Status:
Not open for further replies.

Share This Page