【问题标题】:Error while converting a class to byte array and viceversa?将类转换为字节数组时出错,反之亦然?
【发布时间】:2013-11-27 15:42:48
【问题描述】:

我需要将 Object 作为字节数组发送到另一个方法,该方法本身将从对象返回另一个字节数组。

这是我得到的调用方法的代码:

byte[] bytesArray;
Gato gatito = null;
Gato gato = new Gato();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;

try {

out = new ObjectOutputStream(bos);   
out.writeObject(gato);
bytesArray = bos.toByteArray();
} 

finally {
out.close();
bos.close();
}

System.out.println("Gatito es nulo? "+gatito==null);
byte[] huntedCat = cliente.method(bytesArray);

ByteArrayInputStream bis = new ByteArrayInputStream(huntedCat);
ObjectInput in = null;
try {
in = new ObjectInputStream(bis);
gatito = ((Gato)in.readObject()); 
} finally {
bis.close();
in.close();
}

System.out.println(gatito.nombre);


}

所以这是调用的方法,它实际上执行完全相同的操作:

public byte[] method(byte[] something) {

  byte[] bytesArray = null;
  Gato gato = new Gato();
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutput out = null;

  try {

    out = new ObjectOutputStream(bos);   
    out.writeObject(gato);
    bytesArray = bos.toByteArray();
    out.close();
    bos.close();

  } 
  catch(IOException e) {

  }

  return bytesArray;
}

我总是收到一个错误,所以程序停止并且来自异常的getMessageGato 这是我要转换为字节数组的类。

【问题讨论】:

  • 不要吞下你的异常,处理它们。
  • 错误是什么?使用 try...catch...finally。你忽略了例外

标签: java stream bytearray


【解决方案1】:

会不会是你的Gato 类没有实现Serializable

请参阅:Serializable (JavaDocs)

【讨论】:

    猜你喜欢
    • 2015-02-16
    • 2013-11-11
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多