我有许多使用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();
}
}发布于 2013-01-25 19:55:27
好了现在找到了。这就是问题所在:
byte[] fileArray=org.apache.commons.io.IOUtils.toByteArray("obj.data");那种方法不像你想的那样做:
使用平台的默认字符编码作为byte[]获取字符串的内容。
它根本没有加载文件。
如果您使用此方法,则:
byte[] fileArray =
org.apache.commons.io.FileUtils.readFileToByteArray(new File("obj.data"));..。然后正确地恢复数据。
(就我个人而言,我更喜欢番石榴这类事情,顺便说一句.)
https://stackoverflow.com/questions/14528229
复制相似问题