加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中使用字节数组序列化类

发布时间:2020-12-15 04:26:44 所属栏目:Java 来源:网络整理
导读:我在 Java中有一个带字节数组的类.当我序列化和反序列化类的对象时,字节数组的值正在改变. 我该如何解决这个问题? 请参阅示例代码: public class Test implements Serializable{private static final long serialVersionUID = 3455892176538865707L;public
我在 Java中有一个带字节数组的类.当我序列化和反序列化类的对象时,字节数组的值正在改变.

我该如何解决这个问题?

请参阅示例代码:

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;
}
}

输出:

Byte Array Before serialization : [B@15db9742
Byte Array After deserialization : [B@75b84c92

解决方法

字节数组的值不会改变.您只是打印数组的toString()表示.

将使用java.lang.Object中的默认toString()实现.

因为初始和反序列化的数组不是相同的对象(它们是具有相同内容的两个独立对象),所以它们将具有不同的hashCode(). Java中的数组不会覆盖equals()和hashCode().

您应该使用Arrays.toString()来打印数组的内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读