How to convert object of class into hexadecimal array in java

↘锁芯ラ 提交于 2021-02-05 08:28:07

问题


An object of class having some data and I am gone write that object into java card. I am having a function that convert hexadecimal data into byte array and then write that data to smart card using java card. While i convert data into hex format i encrypt that data. So i need to convert object of class into hexadecimal. Please tell me how to convert object into Hex format in java.

I am using smart card type = contact card using java card 2.2.2 with jcop using apdu.


回答1:


Here i am sending you program which converts objects to byte array and vice versa.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

public class Sandbox {
  public static void main(String[] args) {
    try {
      // convert object to bytes
      Date d1 = new Date();
      System.out.println(d1);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(d1);
      byte[] buf = baos.toByteArray();

      // convert back from bytes to object
      ObjectInputStream ois =
        new ObjectInputStream(new ByteArrayInputStream(buf));
      Date d2 = (Date) ois.readObject();
      ois.close();

      System.out.println(d2);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    }
  }
}



回答2:


You may use serialization but to serialize an object a (that) class must be serializable. Have a look at - Java Object Serialization Specification.




回答3:


Here You can convert class object to byte array as

    public byte[] toByteArray (Object obj)
    {
      byte[] bytes = null;
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try {
        ObjectOutputStream oos = new ObjectOutputStream(bos); 
        oos.writeObject(obj);
        oos.flush(); 
        oos.close(); 
        bos.close();
        bytes = bos.toByteArray ();
      }
      catch (IOException ex) {
        //TODO: Handle the exception
  }
  return bytes;
}


来源:https://stackoverflow.com/questions/8499663/how-to-convert-object-of-class-into-hexadecimal-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!