Serializing classes using byte arrays in Java
•
Java
I have a class with byte array in Java When I serialize and deserialize class objects, the value of the byte array is changing
How can I solve this problem?
See example code:
public class Test implements Serializable{ private static final long serialVersionUID = 3455892176538865707L; public byte[] datakey; public static void main(String[] args) { byte[] key=new byte[16]; Random rn = new Random(); //Trying to randomize the byte array to use as a cryptographic key rn.nextBytes(key); Test test = new test(); test.datakey=key; System.out.println("Byte Array Before serialization : "+test.datakey); test.serializeTest(test); Test loadedtest=test.deserializetest(); System.out.println("Byte Array After deserialization : "+loadedtest.datakey); } public void serializeTest(Test test) { FileOutputStream fos; try { fos = new FileOutputStream("test.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(test); oos.flush(); oos.close();; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Test deserializetest() { Test test=null; String f="test.out"; try { FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); test = (Test)ois.readObject(); ois.close(); fis.close(); } catch(FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return test; } }
Output:
Byte Array Before serialization : [B@15db9742 Byte Array After deserialization : [B@75b84c92
Solution
The value of the byte array does not change You just print the toString () representation of the array
Will use Java The default toString () implementation in lang.Object
Because the initial and deserialized arrays are not the same object (they are two independent objects with the same content), they will have different hashcode() Arrays in java do not override equals() and hashcode()
You should use arrays Tostring() to print the contents of the array
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码