Serialization to Byte Array

Serialization to Byte Array

Question:
How can I convert a class instance to a byte array and thensubsequently reconstruct the original class from the byte array?

Answer:
Java’s Object Serialization API allows you to write class instancesto streams. In order to store a class instance in a byte arrayyou can wrap a ByteArrayOutputStream with an ObjectOutputStream.

To read a class instance from a byte array you can wrap anObjectInputStream with a ByteArrayInputStream. You justhave to remember that all serializable objects must implementthe Serializable interface. The following example demonstrateshow to do this.

import java.io.*;public class ByteSerialize {  public static void main(String[] args) {    Integer write, read;    ObjectOutputStream out;    ObjectInputStream in;    ByteArrayOutputStream byteStream;    byte[] bytes;    write = new Integer(5);    System.out.println("write: " + write);    try {      byteStream = new ByteArrayOutputStream();      out = new ObjectOutputStream(byteStream);      out.writeObject(write);      out.close();      // Byte representation of integer      bytes = byteStream.toByteArray();      in = new ObjectInputStream(new ByteArrayInputStream(bytes));      read = (Integer)in.readObject();      in.close();    } catch(IOException ioe) {      ioe.printStackTrace();      return;    } catch(ClassNotFoundException cnfe) {      cnfe.printStackTrace();      return;    } catch(ClassCastException cce) {      cce.printStackTrace();      return;    }    System.out.println("read : " + read);  }}
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of