我使用ObjectOutputStream将许多对象写入磁盘。在阅读期间,出于某些实现原因,我首先将文件检索为ByteArray,我想读取缓冲数组并从中解码数据。这是一段代码片段
byte [] fileArray=org.apache.commons.io.IOUtils.toByteArray(filePath);
ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(fileArray));
while(true){
Records pos=(Records)in.readObject();
}
但是,我收到此错误
java.io.StreamCorruptedException: invalid stream header: 2F6C6F63
总之,我想将文件加载到内存中,然后在阅读时解码对象而不是磁盘。
该文件写为:
fout=new FileOutputStream(filePath);
bos=new ByteArrayOutputStream();
oos=new ObjectOutputStream(bos);
for(int i=0;i<size;i++){
oos.writeObject(list.get(i));
}
oos.flush();
bos.writeTo(fout);
bos=null;
oos=null;
fout.flush();
fout.close();
oos根本没有关闭!
以下是重现错误的完整示例:
import java.util.*;
import java.io.*;
import org.apache.commons.io.IOUtils.*;
public class Example{
private int[] data;
public Example(){
data=new int[40];
}
public void generate(){
for(int i=0;i<data.length;i++){
data[i]=i;
}
System.out.println("Data generated!");
}
public void write(){
FileOutputStream fout=null;
ByteArrayOutputStream bos=null;
ObjectOutputStream oos=null;
try{
fout=new FileOutputStream("obj.data");
bos=new ByteArrayOutputStream();
oos=new ObjectOutputStream(bos);
for(int i=0;i<data.length;i++){
oos.writeObject((Integer)data[i]);
}
oos.flush();
bos.writeTo(fout);
bos=null;
oos=null;
fout.flush();
fout.close();
}catch(IOException ioe){}
System.out.println("Data written!");
}
public void read(){
ObjectInputStream in=null;
try{
byte[] fileArray=org.apache.commons.io.IOUtils.toByteArray("obj.data");
in=new ObjectInputStream(new ByteArrayInputStream(fileArray));
while(true){
Integer data=(Integer)in.readObject();
}
}catch (EOFException eofe){
try{
in.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
System.out.println("Data read!");
}
public static void main(String[] args){
Example example=new Example();
example.generate();
example.write();
example.read();
}
}
答案 0 :(得分:3)
好的,现在就找到了。这就是问题所在:
byte[] fileArray=org.apache.commons.io.IOUtils.toByteArray("obj.data");
That method没有按照您的想法行事:
使用平台的默认字符编码将String的内容作为byte []获取。
根本没有加载文件。
如果你改用它:
byte[] fileArray =
org.apache.commons.io.FileUtils.readFileToByteArray(new File("obj.data"));
...然后数据正确恢复。
(就我个人而言,我更喜欢Guava这样的事情......)