Abhineet Kumar
Abhineet Kumar

Reputation: 29

Change in file after creating FileOutputStream object even without writing anything into file

EDIT (for the sake of confusion): null has been written into the files "abc" and "efg".

After running the following code, the contents of file "abc" change which were initially null , and I get EOFException in every next execution :

ObjIStream = new ObjectInputStream(new FileInputStream("abc"));
M[][] objs  = (M[][]) ObjIStream.readObject();
FS.objs = objs;
ObjIStream.close();

Here, FS.objs is a static member of class FS of type M[][] type.

On the other hand, this one has no effect on the file and I don't get any Exceptions after any number of executions:

ObjIStream = new ObjectInputStream(new FileInputStream("abc"));
M[][] objs  = (M[][]) ObjIStream.readObject();
ObjIStream.close();

EDIT: I just found the trouble that exists in class FS in this form:

static{ 
 try { 
  ObjOStream = new ObjectOutputStream(new FileOutputStream("abc"));
  ObjOStream.close();
  ObjOStream = new java.io.ObjectOutputStream(new java.io.FileOutputStream("efg"));
  ObjOStream.close(); 
 } 
 catch (IOException ex) { } 
}

How is it troubling anyways?

Upvotes: 0

Views: 1417

Answers (1)

Abhineet Kumar
Abhineet Kumar

Reputation: 29

The problem is new FileOutputStream("abc") itself, which means new FileOutputStream("abc", false). It cleans up all the data in file because you are not going to append anything. It calls FileOutputStream.open(String name, boolean append) which is a private native function. It erases everything in file in overwrite mode.

Upvotes: 1

Related Questions