Dear listmembers,
I have a problem using FileOutputStreams. I want to be able to append to
an existing file, and I would like to be able to read the information back
later.
To write to the file, I use the following small program, in which a
FileOutputStream is opened in append-mode, followed by the writing of two
Strings:
///////////////////////////////////////////////////////////
import java.io.*;
public class writer
{
public static void main(String argv[])
{
try
{
FileOutputStream
f = new FileOutputStream("out", true); // open in append mode
ObjectOutputStream
o = new ObjectOutputStream(f);
o.writeObject("hello"); // write 2 strings
o.writeObject("world");
o.flush();
f.close();
}
catch (Exception e)
{
System.err.println(e.toString());
}
}
}
//////////////////////////////////////////////////////
Then, to read the file again, I use the following small program:
//////////////////////////////////////////////////////
import java.io.*;
public class reader
{
public static void main(String argv[])
{
try
{
FileInputStream
f = new FileInputStream("out");
ObjectInputStream
o = new ObjectInputStream(f);
while (true)
System.err.println("Saw: " + (String)o.readObject());
}
catch (Exception e)
{
System.err.println(e.toString());
}
}
}
////////////////////////////////////////////////////////////
Now, after running writer the first time, 'out' is created, and contains
(hex):
00000000: AC ED 00 05 74 00 05 68 65 6C 6C 6F 74 00 05 77 ....t..hellot..w
00000010: 6F 72 6C 64 orld
The reader program reads this, and shows:
Saw: hello
Saw: world
java.io.EOFException: Expecting code
So far, so good. Now I run writer again, and this results in the following
contents of the file 'out':
00000000: AC ED 00 05 74 00 05 68 65 6C 6C 6F 74 00 05 77 ....t..hellot..w
00000010: 6F 72 6C 64 AC ED 00 05 74 00 05 68 65 6C 6C 6F orld....t..hello
00000020: 74 00 05 77 6F 72 6C 64 t..world
Note the byte at offset 0x14: it is 0xac, which is -84 when the byte is viewed
as a signed 8 bits value. When I now run reader, it tells me:
Saw: hello
Saw: world
java.io.StreamCorruptedException: Type code out of range, is -84
What I make of this is that the initial bytes of the file (ac ed) are
appended every time the writer program is started again. The first time I
start writer the two strings are written consecutively, without any special
bytes in between. So it looks as if the intermediate ac ed bytes shouldn't be
there.
So, I wonder if I'm doing something wrong here. If any of you guys could help
me out (maybe by sending email directly to [EMAIL PROTECTED]), I'd be very
grateful.
Thanks in advance,
--
Frank B. Brokken (al sinds enige jaren uitgedost (untranslatable))
My extended signature is at http://www.icce.rug.nl/frank/signature
----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]