I'm appending Object with that code.
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();
}
}
And that writes it on my file correctly with writeObject methos, but when i use the "readObject()" with the "objectinputStream".
More information: I've used "readObjectOverride"(using a subclass) and it has give me the same error.
It appeared that error:
"invalid stream header: 79757200."
I solucionated this error BUT it read the ".dat" file incorrectly.
My file .dat had 4 rows but i only read 1 row. My code for reading is that:
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);
It only shows me the last row.
I write my rows like that:
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)
I find my owm misunderstanding. I' am reader other ask and answers of stack overflow.
First i had written my file correctly with 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();
}
}
Read my file like that:
ObjectInputStream objetoInStr = new ObjectInputStream(new FileInputStream(sPath))
{
protected void readStreamHeader() throws IOException
{
}
};
And finally read my object like that:
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);
}
And all of that id the solution. I'll hope helps other programmers like me.