4

我有许多使用 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();
    }


}
4

1 回答 1

3

好的,现在找到了。这就是问题:

byte[] fileArray=org.apache.commons.io.IOUtils.toByteArray("obj.data");

该方法不会像您认为的那样做:

使用平台的默认字符编码将 String 的内容作为 byte[] 获取。

它根本不加载文件

如果您改用它:

 byte[] fileArray = 
     org.apache.commons.io.FileUtils.readFileToByteArray(new File("obj.data"));

...然后数据被正确恢复。

(顺便说一下,我个人更喜欢番石榴来做这种事情......)

于 2013-01-25T19:55:27.450 回答