ObjectInputStream / ObjectOutputStream:读取/写入追加对象的错误

时间:2016-02-25 17:07:08

标签: java objectinputstream objectoutputstream

我用该代码附加Object。

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class ClaseAppendObjectStream extends ObjectOutputStream 
{
     public ClaseAppendObjectStream(OutputStream os) throws IOException 
     {
        super(os);
     }

     protected void writeStreamHeader() throws IOException 
     {  
         reset();
     }

 }

并且使用writeObject方法正确地将它写在我的文件中,但是当我使用" readObject()"使用" objectinputStream"。

更多信息:      我已经使用过" readObjectOverride"(使用子类)并且它给了我同样的错误。

出现了错误:

"无效的流标题:79757200。"

我解决了这个错误但它读了" .dat"文件不正确。

我的文件.dat有4行,但我只读了1行。我的阅读代码是:

ObjectInputStream objetoInStr = new ObjectInputStream(new FileInputStream(sPath))
{
    protected void readStreamHeader() throws IOException 
    {
    }
};

ClassEmployer[] getData = (ClassEmployer[])objetoInStr.readObject();

objetoInStr.close();
String sPhrase="";                      
for(ClassEmployer e : getData )
{
   sPhrase=sPhrase+"Name: " + e.getName() + " Salary: "+ e.getSalary();
}   
objTPane.setText(sPhrase);

它只显示最后一行。

我写这样的行:

ClassEmployer[] employers= new ClassEmployer[1];
employers[0]= new ClassEm,ployer(objctotext1.getText().trim(),objecttext2.getText().trim());

FileOutputStream objetoFileOutputStream = new FileOutputStream(sPath,true);
BufferedOutputStream objetooutputBuffer = new BufferedOutputStream(objetoFileOutputStream);

ClaseAppendObjectStream objetoOutStr = new ClaseAppendObjectStream(objetooutputBuffer);
objetoOutStr.writeObject(employers) 

1 个答案:

答案 0 :(得分:0)

我发现自己的错误。我'读者其他问题和堆栈溢出的答案。

首先我用AppendClass正确编写了我的文件:

 import java.io.IOException;
 import java.io.ObjectOutputStream;
 import java.io.OutputStream;

 public class ClaseAppendObjectStream extends ObjectOutputStream 
 {
      public ClaseAppendObjectStream(OutputStream os) throws IOException 
      {
          super(os);
      }

     protected void writeStreamHeader() throws IOException 
     {  
          reset();
     } 

 }

像这样阅读我的文件:

ObjectInputStream objetoInStr   = new ObjectInputStream(new FileInputStream(sPath))
{
    protected void readStreamHeader() throws IOException 
    {
    }
};

最后像这样阅读我的对象:

ClassEmployer Employer;                     

String sText="";
try
{       
    //Infinit reading
    while(true)
    {
        //that code wil have crashed with an EOFEXception
        Employer = (ClasseEmployer)objetoInStr.readObject();
        sText=sText+"Name: " + Employer.getName() + " Salary: "+ Employer.getSalary() +"\n";
    }   
}
catch(EOFException ex)
{
    objetotextoGrande.setText(sText);
}

所有这些都是解决方案。我希望能帮助像我这样的其他程序员。