Skip to content

Instantly share code, notes, and snippets.

@aadnk
Created December 26, 2013 20:17
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aadnk/8138186 to your computer and use it in GitHub Desktop.
Save aadnk/8138186 to your computer and use it in GitHub Desktop.
Serialize and deserialize inventories to a string.
package com.comphenix.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
public class BukkitSerialization {
public static String toBase64(Inventory inventory) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
// Write the size of the inventory
dataOutput.writeInt(inventory.getSize());
// Save every element in the list
for (int i = 0; i < inventory.getSize(); i++) {
dataOutput.writeObject(inventory.getItem(i));
}
// Serialize that array
dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e);
}
}
public static Inventory fromBase64(String data) throws IOException {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt());
// Read the serialized inventory
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, (ItemStack) dataInput.readObject());
}
dataInput.close();
return inventory;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e);
}
}
}
@aadnk
Copy link
Author

aadnk commented Jan 6, 2014

Unfortunately, looks like this version doesn't support attributes (in #2982). I recommend using this version if that is a concern.

@eUipKh
Copy link

eUipKh commented Sep 3, 2017

Works perfect with 1.12 version, thanks for this!

@RedstoneCommands
Copy link

When im Using this my Console shows "Chests must have a size that is a multiple of 9!"

@VylariaGit
Copy link

Its possible to have exemple ?

@abhithedev200
Copy link

can i Serialize player inventory?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment