Guest User

Untitled

a guest
Jul 18th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import com.google.common.collect.Maps;
  2. import com.google.common.io.ByteStreams;
  3. import org.junit.Test;
  4.  
  5. import java.io.ByteArrayInputStream;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.ObjectInputStream;
  12. import java.io.ObjectOutputStream;
  13. import java.util.Map;
  14.  
  15. import static org.junit.Assert.assertTrue;
  16.  
  17. /**
  18. * Java Serialization Sample Code.
  19. * <p/>
  20. */
  21. public class JavaSerializationTest {
  22.  
  23. @Test
  24. public void serializeDeserialize() throws IOException, ClassNotFoundException {
  25.  
  26. final String outputFilePath = "/tmp/object.ser";
  27.  
  28. // Sample object
  29. Map object = Maps.newHashMap();
  30. object.put("a", "b");
  31.  
  32. // Do serialize object
  33. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  34. ObjectOutputStream oos = new ObjectOutputStream(bos);
  35. oos.writeObject(object);
  36. oos.flush();
  37. oos.close();
  38. bos.close();
  39. byte[] bytes = bos.toByteArray();
  40.  
  41. // Write to file
  42. FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
  43. fileOutputStream.write(bytes);
  44. fileOutputStream.close();
  45.  
  46. assertTrue(new File(outputFilePath).isFile());
  47.  
  48. // Do deserialize object
  49. FileInputStream fileInputStream = new FileInputStream(outputFilePath);
  50. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(ByteStreams.toByteArray(fileInputStream));
  51. ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
  52. Object readObject = objectInputStream.readObject();
  53. System.out.println(readObject);
  54.  
  55. assertTrue(readObject instanceof Map);
  56. }
  57. }
Add Comment
Please, Sign In to add comment