I'm working on a Java File I/O Interface, I need my files to be in binary format, not in strings. I've found ObjectOutputStream and ObjectInputStream useful for my needs, but I need the interface to be able to write at the end of my file, as of I need it to record future data in the same file over and over.
I tried using the FileOutputStream(String file, boolean append) constructor but since my class implements Serializable there seems to be an issue. When it attempts to read a second record it throws a StreamCorruptedException. I know it must be because there's this header that kind of describes the object's fields.
My question is, how can I store objects succesfully? I like using objects, because it makes it easier to structure and handle data. This is my code so far:
try
{
FileOutputStream outFile;
ObjectOutputStream outStream;
FileInputStream inFile;
ObjectInputStream inStream;
outFile = new FileOutputStream("people.mcf", true);
outStream = new ObjectOutputStream(outFile);
//Writing the objects
System.out.println("Writing file...");
for(int i = 0; i < 3; i++)
{
outStream.writeObject(people[i]);
}
System.out.println("Finished writing file...");
outFile.close();
outStream.close();
//Reading the files
System.out.println("Attempting to read file...");
inFile = new FileInputStream("people.mcf");
inStream = new ObjectInputStream(inFile);
Person buffer;
while(true)
{
buffer = (Person)inStream.readObject();
System.out.println(buffer.getData());
}
}
catch(EOFException e)
{
System.out.println("Reached end of file...");
}
catch(IOException e)
{
System.err.println(e.toString());
}
This is the Person class:
static class Person implements Serializable
{
private final String name;
private final int age;
private final String address;
public Person(String name, int age, String address)
{
this.name = name;
this.age = age;
this.address = address;
}
public String getData()
{
return name + " " + age + " " + address;
}
}
This is the output I get:
Writing file...
Finished writing file...
Attempting to read file...
Andres 26 Palo Gordo
Pilar 22 Palo Gordo
Kelvin 27 Palo Gordo
java.io.StreamCorruptedException: invalid type code: AC
BUILD SUCCESSFUL (total time: 0 seconds)
EDIT: I'm not asking why I'm getting the StreamCorruptedException, I'm aware that ObjectOutputStream is causing this, what I'm asking for is another way to store Object data in a structured manner.