我正在使用函数toByteBuffer()
来序列化一些数据。请注意,我使用DataOutputStream
来编写序列化数据。
public ByteBuffer toByteBuffer() throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(bs);
int klistSize = 128;
ds.writeInt(klistSize); /* writes KListSize*/
for (int klistIndex = 0; klistIndex < klistSize; klistIndex++) {
Double freq = klistIndex * 12.2;
ds.writeDouble(freq);
ds.writeInt(klistIndex);
for (int i = 0; i < klistIndex; i++) {
Double l1 = (double) (System.currentTimeMillis() / 1000);
Double l2 = (double) (System.currentTimeMillis() / 1000);
ds.writeDouble(l1);
ds.writeDouble(l2);
}
}
ds.flush();
return ByteBuffer.wrap(bs.toString().getBytes(charset));
}
然后在我的项目中,我使用函数fromByteBuffer(ByteBuffer byteBuffer)
来反序列化数据。请注意,我使用DataInputStream
来读取序列化数据。
public void fromByteBuffer(ByteBuffer byteBuffer) throws IOException {
DataInputStream ds = new DataInputStream(new ByteArrayInputStream(charset.decode(byteBuffer).toString().getBytes()));
int klistSize = ds.readInt();
for (int i = 0; i < klistSize; i++) {
Double freq = ds.readDouble();
System.out.print("freq : " + freq + ", ");
int entryCount = ds.readInt();
System.out.print("count : " + entryCount + " ");
for(int j = 0; j< entryCount; j++)
{
double[] f1 = new double[2];
f1[0] = ds.readDouble();
f1[1] = ds.readDouble();
}
}
}
但由于某种原因,我收到以下错误。
freq : -0.11328125, count : 0 freq : 3.485250766913E-310, count : 1717960704 Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readLong(DataInputStream.java:416)
at java.io.DataInputStream.readDouble(DataInputStream.java:468)
at ucr.edu.Main.fromByteBuffer(Main.java:67)
at ucr.edu.Main.main(Main.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
以上代码是我用于项目的代码的简化版本,但它们仍然会出现相同的错误。
此异常的原因是什么?如何解决此问题?
答案 0 :(得分:2)
出于某种原因,您要将ByteBuffer
转换为String
并将其转回。这通常是一个坏主意。
在您的toByteBuffer
代码中,请写下以下内容:
ByteBuffer.wrap(bs.toByteArray());
在您的fromByteBuffer
方法中,例如:
// to read the byteBuffer from the beginning, you might want to rewind
// before copying it to an array:
// byteBuffer.rewind();
byte[] array = new byte[byteBuffer.remaining()];
byteBuffer.get(array);
DataInputStream ds = new DataInputStream(new ByteArrayInputStream(array));
祝你好运。