问题
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