如何通过将 ByteArrayOutputStream 复制到 ByteArray 来克隆对象,然后通过 ByteArrayInputStream 调用它?
How to clone an Object by copy ByteArrayOutputStream into ByteArray, then call it by ByteArrayInputStream?
我尝试通过以下方式克隆对象:1) 将其推入 ByteArrayOutputStream 2) 将流分配给字节数组 3) 通过 ByteArrayInputStream 读取字节数组。但是,这行不通,因为我无法将 OutputStream 分配给字节数组,该行将不会执行。
Apporach 基于 Java Serializable Object to Byte Array
public Bank clone() {
Bank objektKopie = null;
byte[] byteKopie = null;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = null;
try {
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(this);
oo.flush() ;
byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
bo.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
ObjectInputStream oi = null;
try {
oi = new ObjectInputStream(bi);
objektKopie = (Bank) oi.readObject();
} catch (Exception e) { System.out.println(e.getMessage()); }
return objektKopie;
}
您的代码抛出 "NotSerializable" 异常,您的 class 银行需要实现 Serializable
如果依赖关系没问题,GSON 可以很容易地做到这一点
我尝试通过以下方式克隆对象:1) 将其推入 ByteArrayOutputStream 2) 将流分配给字节数组 3) 通过 ByteArrayInputStream 读取字节数组。但是,这行不通,因为我无法将 OutputStream 分配给字节数组,该行将不会执行。
Apporach 基于 Java Serializable Object to Byte Array
public Bank clone() {
Bank objektKopie = null;
byte[] byteKopie = null;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = null;
try {
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(this);
oo.flush() ;
byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
bo.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
ObjectInputStream oi = null;
try {
oi = new ObjectInputStream(bi);
objektKopie = (Bank) oi.readObject();
} catch (Exception e) { System.out.println(e.getMessage()); }
return objektKopie;
}
您的代码抛出 "NotSerializable" 异常,您的 class 银行需要实现 Serializable
如果依赖关系没问题,GSON 可以很容易地做到这一点