I want to serialize a same object on file, each time when i run a program. This is a simple algorithm to explain my problem.
In the begening i store a String
on writer
. in the last i read a file.
The goal of this program is if i run my program X time, i store and i print on screen X time my object.
class ReadFile {
static ObjectOutputStream writer = null;
public static void main(String[] args) throws IOException, ClassNotFoundException {
writer = new ObjectOutputStream(new FileOutputStream("trace", true));
store("String");
if (writer != null) {
writer.close();
}
open("file.tmp");
}
static public void store(String chaine) {
if (writer == null) {
return;
}
try {
writer.writeObject(chaine);
} catch (IOException ex) {
}
}
static public void open(String file) throws FileNotFoundException, IOException, ClassNotFoundException {
StringBuilder str = new StringBuilder();
ObjectInputStream objs;
try {
objs = new ObjectInputStream(new FileInputStream(file));
try {
while (true) {
Object obj = objs.readObject();
str.append(obj.toString());
}
} catch (EOFException ex) {
}
objs.close();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
}
When i run this program i have this error :
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at ReadFile.open(ReadFile.java:47)
at ReadFile.main(ReadFile.java:35)
What can i do please ?
According to this post you cannot append to a ObjectOutputStream, which you are trying to do by opening the underlying FileOutputStream in append mode. There is a solution mentioned on that post such that you create an AppendableObjectOutputStream , or you could just open the FileOutputStream without appending.