Showing posts with label byte array. Show all posts
Showing posts with label byte array. Show all posts

Thursday, 18 August 2022

Java: convert byte[] to object and object to byte[]

Following snippet convert serializable object to byte array.

public static byte[] serialize(Serializable serializable) {

    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
        objectOutputStream.writeObject(serializable);
        objectOutputStream.flush();
        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

 

Following snippet convert the byte array to object.

public static Object deserialize(byte[] byteArray) {
    try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
        return objectInputStream.readObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

 

Find the below working application.

 


User.java

 

package com.sample.app.dto;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 198623L;

    private int id;

    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

SerializationDemo.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.sample.app.dto.User;

public class SerializationDemo {

    public static byte[] serialize(Serializable serializable) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static Object deserialize(byte[] byteArray) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        byte[] byteArr = serialize(new User(1, "Krishna"));
        User user = (User) deserialize(byteArr);

        System.out.println("Byte array representaion of user object :");
        for (byte b : byteArr) {
            System.out.print(b + " ");
        }

        System.out.println("\n\nDeserialized version of user object from byte array : ");
        System.out.println("user : " + user);
    }

}

Output

Byte array representaion of user object :
-84 -19 0 5 115 114 0 23 99 111 109 46 115 97 109 112 108 101 46 97 112 112 46 100 116 111 46 85 115 101 114 0 0 0 0 0 3 7 -33 2 0 2 73 0 2 105 100 76 0 4 110 97 109 101 116 0 18 76 106 97 118 97 47 108 97 110 103 47 83 116 114 105 110 103 59 120 112 0 0 0 1 116 0 7 75 114 105 115 104 110 97 

Deserialized version of user object from byte array : 
user : User [id=1, name=Krishna]


You may like

Java: Convert byte array to object

It is pretty simple with serialization. Just read the Serializable object from ObjectInputStream.

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Serializable serializable = objectInputStream.readObject();

 

Find the below working application.

 


User.java
package com.sample.app.dto;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 198623L;

    private int id;

    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

SerializationDemo.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.sample.app.dto.User;

public class SerializationDemo {

    public static byte[] serialize(Serializable serializable) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static Object deserialize(byte[] byteArray) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        byte[] byteArr = serialize(new User(1, "Krishna"));
        User user = (User) deserialize(byteArr);

        System.out.println("Byte array representaion of user object :");
        for (byte b : byteArr) {
            System.out.print(b + " ");
        }

        System.out.println("\n\nDeserialized version of user object from byte array : ");
        System.out.println("user : " + user);
    }

}

Output

Byte array representaion of user object :
-84 -19 0 5 115 114 0 23 99 111 109 46 115 97 109 112 108 101 46 97 112 112 46 100 116 111 46 85 115 101 114 0 0 0 0 0 3 7 -33 2 0 2 73 0 2 105 100 76 0 4 110 97 109 101 116 0 18 76 106 97 118 97 47 108 97 110 103 47 83 116 114 105 110 103 59 120 112 0 0 0 1 116 0 7 75 114 105 115 104 110 97 

Deserialized version of user object from byte array : 
user : User [id=1, name=Krishna]


You may like

How to convert an object to byte array in java?

Step 1: Make the class serializable by implementing Serializable interface.

public class User implements Serializable {
    .......
    .......
}

 

Step 2: Write the Serializable object to ObjectOutputStream, make sure that ObjectOutputStream is internally using ByteArrayOutputStream.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializable);
objectOutputStream.flush();

 

Step 3: Get the byte array from ByteArrayOutputStream.

byte[] byteArr = byteArrayOutputStream.toByteArray();

 

Find the below working application.

 

User.java

 

package com.sample.app.dto;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 198623L;

    private int id;

    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

 

SerializationDemo.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.sample.app.dto.User;

public class SerializationDemo {

    public static byte[] serialize(Serializable serializable) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static Object deserialize(byte[] byteArray) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        byte[] byteArr = serialize(new User(1, "Krishna"));
        User user = (User) deserialize(byteArr);

        System.out.println("Byte array representaion of user object :");
        for (byte b : byteArr) {
            System.out.print(b + " ");
        }

        System.out.println("\n\nDeserialized version of user object from byte array : ");
        System.out.println("user : " + user);
    }

}

 


Output

Byte array representaion of user object :
-84 -19 0 5 115 114 0 23 99 111 109 46 115 97 109 112 108 101 46 97 112 112 46 100 116 111 46 85 115 101 114 0 0 0 0 0 3 7 -33 2 0 2 73 0 2 105 100 76 0 4 110 97 109 101 116 0 18 76 106 97 118 97 47 108 97 110 103 47 83 116 114 105 110 103 59 120 112 0 0 0 1 116 0 7 75 114 105 115 104 110 97 

Deserialized version of user object from byte array : 
user : User [id=1, name=Krishna]

 

You may like

Sunday, 6 March 2022

File programs in Java

      Get File path separator
      Java Properties file
      Compress and archive files in zip format
      Decompress files from zip file
      File utilities application using Guava package
      Check contents of two files are equal or not
      Encrypt and decrypt XML file in Java
      Create Password Protected zip file in Java
      Place a file in project class path
      Accessing meta data of a file (All attributes of file)
      Set Unique Identifier to File in Java
      Set File permissions in Java
      File Tail implementation in Java
      Launch URI Scheme over java file
      DigestInputStream & DigestOutputStream Example
      Move file to recycle bin
      Generate content hash of a file
      HOW TO GENERATE SHA1 HASH VALUE OF FILE
      HOW TO GENERATE MD5 HASH VALUE OF FILE
      List contents of a zip file
      Split file path using system file separator symbol
      Split the string using file Path separator
      File.separator vs File.pathSeparator
      Encrypt and Decrypt file/stream in Java
      Print all the file names recursively
      How to write multiple input streams to a file
      Working with RandomAccessFile in Java
      Java write to a file using BufferedWriter
      Java write to a file using FileWriter
       Java: Programmatically import certificate to cacerts file
      Apache commons io: Download a file from url
      Convert xml file to csv
      Redirect System.out.println statements to a stream or file
      Redirect System.err.println statements to a stream or file
      Append text to a file
      Create and write text content to a file
      Create and write byte array to a file
      Read plain text file in Java
      Copy file from one location to another
      Search for files in a folder
       Print all the file names in a directory and sub directories
      Read last n lines of a file
      Escape equal sign in properties file
      Open a file
      Convert InputStream to ByteArray
      Convert file to byte array
      Java: Get content hash of the file
      Read file content as string
      Read file content as string in one line
      Get file name by removing extension
      Sort the files by their last modified date
      Sort files by their name
      Sort files by their size
      Get File size in java
      List files by their created time
      Create file parent directories if they are not exist
      Get file name from absolute path
      Count number of lines in a file
      Download file from Internet using Java
      Get the content of resource file as string
      Get the resource file path
      Copy the content of file to other location
      Write byte array to a file
      How to download a binary file in Java?
      How to process a huge file in Java?
      How to process a large file in chunks?
      How to get the directory size in Java?
      Convert OutputStream to String in Java
      Convert string to InputStream in Java
      Read the data from BufferedReader in Java
      Read file content using BufferedReader in Java
      Touch the file in Java (Update the file timestamp)
      Get POSIX file attributes in Java
      Get file basic file attributes in Java
      check whether a file is executable or not in Java
      Check whether a directory has some files or not in Java
      Check given path is a file and not a symbolic link in Java
      Check given path is a directory and not a symbolic link in Java
      Convert InputStream to string in Java
      Write InputStream to a file in Java
      File separator, separatorChar, pathSeparator, pathSeparatorChar in Java
      Implement an Output stream that writes the data to two output streams
      Check whether directory can be accessed and has read and write privileges in Java
      Get the hash or message digest of a file in Java
      Copy InputStream to OutputStream in Java

Friday, 1 May 2020

Javassist: Get CtClass object from byte array

Step 1: Define byte array.
byte[] byteArray = { -54, -2, -70, -66, 0, 0, 0, 52, 0, 12, 1, 0, 26, 99, 111, 109, 47, 115, 97, 109, 112, 108,
                  101, 47, 97, 112, 112, 47, 109, 111, 100, 101, 108, 47, 80, 111, 105, 110, 116, 7, 0, 1, 1, 0, 16, 106,
                  97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 7, 0, 3, 1, 0, 10, 83, 111, 117, 114,
                  99, 101, 70, 105, 108, 101, 1, 0, 10, 80, 111, 105, 110, 116, 46, 106, 97, 118, 97, 1, 0, 6, 60, 105,
                  110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 12, 0, 7, 0, 8, 10, 0, 4, 0, 9, 1, 0, 4, 67, 111, 100, 101, 0,
                  33, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0, 1, 0, 7, 0, 8, 0, 1, 0, 11, 0, 0, 0, 17, 0, 1, 0, 1, 0, 0, 0, 5,
                  42, -73, 0, 10, -79, 0, 0, 0, 0, 0, 1, 0, 5, 0, 0, 0, 2, 0, 6 };

Step 2: Define class name
String className = "com.sample.app.model.Point";

Step 3: Insert a ClassPath object at the head of the search path.
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ByteArrayClassPath(className, byteArray));

Step 4: Get the CtClass object from className.
CtClass cc = pool.get(className);

Find the below working application.

App.java
package com.sample.app;

import javassist.ByteArrayClassPath;
import javassist.ClassPool;
import javassist.CtClass;

public class App {

 public static void main(String args[]) throws Exception {

  String className = "com.sample.app.model.Point";
  byte[] byteArray = { -54, -2, -70, -66, 0, 0, 0, 52, 0, 12, 1, 0, 26, 99, 111, 109, 47, 115, 97, 109, 112, 108,
    101, 47, 97, 112, 112, 47, 109, 111, 100, 101, 108, 47, 80, 111, 105, 110, 116, 7, 0, 1, 1, 0, 16, 106,
    97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 7, 0, 3, 1, 0, 10, 83, 111, 117, 114,
    99, 101, 70, 105, 108, 101, 1, 0, 10, 80, 111, 105, 110, 116, 46, 106, 97, 118, 97, 1, 0, 6, 60, 105,
    110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 12, 0, 7, 0, 8, 10, 0, 4, 0, 9, 1, 0, 4, 67, 111, 100, 101, 0,
    33, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0, 1, 0, 7, 0, 8, 0, 1, 0, 11, 0, 0, 0, 17, 0, 1, 0, 1, 0, 0, 0, 5,
    42, -73, 0, 10, -79, 0, 0, 0, 0, 0, 1, 0, 5, 0, 0, 0, 2, 0, 6 };

  ClassPool pool = ClassPool.getDefault();
  pool.insertClassPath(new ByteArrayClassPath(className, byteArray));
  CtClass cc = pool.get(className);

  System.out.println(cc.getClass());

  cc.writeFile("/Users/Shared/assistDemos");

 }
}

Run App.java, you can see below message in console.

class javassist.CtClassType

You can observe Point.class file is generated at folder /Users/Shared/assistDemos.
$tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
    └── sample
        └── app
            └── model
                └── Point.class

4 directories, 1 file

Open Point.class file from decompiler to see the soure code.


Previous                                                    Next                                                    Home