我在序列化对象时遇到了一些问题(我正在使用 JBoss Drools,并且想要存储 KnowledgePackage 的 ArrayList)。
当我序列化列表,将结果存储在文件中并反序列化它时,没有出现问题,所以它工作正常。
但是当我序列化列表,将结果存储在字节流中,然后将其保存在 JarFile 中时,由于此错误,我无法反序列化结果:
IOException during package import : java.util.ArrayList; local class incompatible: stream classdesc serialVersionUID = 8664875232659988799, local class serialVersionUID = 8683452581122892189
所以我认为问题是当我将序列化对象保存到 Jarfile 条目中时。我认为我这样做是正确的,因为可以正确读取 Jarfile 中以相同方式保存的其他文件。在使用 'cmp' 和 'hexdump' 之后,我发现如果 uuid 将其保存在 jar 中会导致一个八位字节的变化,否则内容是相同的。
我真的很失望,无法说明问题可能出在哪里。
什么可以修改两个类之间的 SerialVersionUID?除了另一个 vm 版本?
添加源代码:exportToJar -> writeRulesPackageEntry -> writeEntry
/**
* Writes content provided from a reader into a file contained in a jar.
*
* @param output the output stream to write on
* @param entryName the name of the file that will contain reader data
* @param contentReader
*
* @return the zip entry that has been created into the jar
*/
ZipEntry writeEntry(JarOutputStream output, String entryName, ByteArrayInputStream input) {
if (output == null || entryName == null || entryName.trim().length() == 0 || input == null) {
throw new NullPointerException("Null argument passed");
}
ZipEntry entry = new ZipEntry(entryName);
byte[] buffer = new byte[BUFFER_LENGTH];
try {
output.putNextEntry(entry);
int nRead;
while ((nRead = input.read(buffer, 0, BUFFER_LENGTH)) > 0) {
output.write(buffer, 0, nRead);
}
output.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
return entry;
}
/**
* Export rules files to a serialized object (ArrayList<KnowledgePackage>) into
* an output stream, then write the output content as an entry of a jar.
*
* @param os the output jar to write in
*/
void writeRulesPackageEntry(JarOutputStream os) {
// serialize objects and write them to the output stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
RulesPackaging rulesPackaging = new RulesPackaging();
rulesPackaging.exportResources(this.rules, output);
// create a new input stream to read written objects from
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
this.writeEntry(os, Product.ENTRY_RULES_PACKAGE, input);
}
/**
* Creates a JarFile containing resources.
*
* @param filename the exported jar filename
* @return the jar as an object, null if an error occured
*/
public JarFile exportToJar(String filename) {
FileOutputStream fOs;
JarOutputStream jOs;
JarFile jar = null;
try {
fOs = new FileOutputStream(filename);
jOs = new JarOutputStream(fOs);
this.writeRulesPackageEntry(jOs);
jOs.close();
// construct a jar from the output jar
jar = new JarFile(new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
return jar;
}