broken-arrow

Untitled

Apr 30th, 2021
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. package org.broken.cheststorage.database.sqlite.more;
  2.  
  3. import org.bukkit.inventory.ItemStack;
  4. import org.bukkit.util.io.BukkitObjectInputStream;
  5. import org.bukkit.util.io.BukkitObjectOutputStream;
  6. import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
  7.  
  8. import java.io.ByteArrayInputStream;
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.IOException;
  11.  
  12. public class SerializDeserialzItemStackFromToDatabase {
  13.  
  14.  
  15. /**
  16. * A method to serialize an {@link ItemStack} array to Base64 String.
  17. * <p>
  18. * <p/>
  19. * <p>
  20. * Based of {@link #toBase64(Inventory)}.
  21. *
  22. * @param items to turn into a Base64 String.
  23. * @return Base64 string of the items.
  24. * @throws IllegalStateException
  25. */
  26. public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException {
  27. try {
  28. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  29. BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
  30.  
  31. // Write the size of the inventory
  32. dataOutput.writeInt(items.length);
  33.  
  34. // Save every element in the list
  35. for (int i = 0; i < items.length; i++) {
  36. dataOutput.writeObject(items[i]);
  37. }
  38.  
  39. // Serialize that array
  40. dataOutput.close();
  41. return Base64Coder.encodeLines(outputStream.toByteArray());
  42. } catch (Exception e) {
  43. throw new IllegalStateException("Unable to save item stacks.", e);
  44. }
  45. }
  46.  
  47. /**
  48. * Gets an array of ItemStacks from Base64 string.
  49. * <p>
  50. * <p/>
  51. * <p>
  52. * Base of {@link #fromBase64(String)}.
  53. *
  54. * @param data Base64 string to convert to ItemStack array.
  55. * @return ItemStack array created from the Base64 string.
  56. * @throws IOException
  57. */
  58. public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException {
  59. try {
  60. ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
  61. BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
  62. ItemStack[] items = new ItemStack[dataInput.readInt()];
  63.  
  64. // Read the serialized inventory
  65. for (int i = 0; i < items.length; i++) {
  66. items[i] = (ItemStack) dataInput.readObject();
  67. }
  68.  
  69. dataInput.close();
  70. return items;
  71. } catch (ClassNotFoundException e) {
  72. throw new IOException("Unable to decode class type.", e);
  73. }
  74. }
  75.  
  76. }
Add Comment
Please, Sign In to add comment