ObjectInputStream/ObjectOutputStream:附加对象错误 reading/Writing

ObjectInputStream/ObjectOutputStream: Errors reading/Writing an appending Objects

我正在用该代码附加对象。

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"(使用子类),它给了我同样的错误。

出现错误:

"invalid stream header: 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) 

我发现自己的误解。我是 reader 堆栈溢出的其他问题和答案。

首先我用 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);
}

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