Reading/Writing binary files
Posted on 2002-03-06
I've been fighting with this problem for a few days and to be honest I'm quite confused as to what's
going on. Here's the scenario...I'm taking a binary file, reading it in to a char buffer, looking
for a particular sequence of characters, changing that sequence to a new sequence (of the same length),
and writing the buffer out to a new file. I then am opening up the two files in a hex editor to see
if my changes worked properly.
Here's where it gets interesting. Upon looking through the file, I find that the sequence I want to
change did get changed properly. However, there are some other changes that were made that shouldn't
The following list of hex values are being incorrectly changed to "3F" (every instance of them...not
just one or two):
Now, when printing out what characters those are, I see that they are some of the "unprintable characters"
(ie '?'). However, a number of other unprintable characters don't get changed to 3F. For example,
the following are left alone:
Also, I know for a fact that this isn't an off by one error, as I'm reading in 8192 bytes at a time,
and writing them out. Since the test file I'm working on only takes 2 reads and writes, and there are
significantly more changes than that, I'm pretty sure that I'm not just losing the last character in
my buffer or anything like that.
Does anybody have any idea what's going on here? I'm using BufferedReader and BufferedWriter for the
read/write operations (also tried FileReader/Writer). I suspect there is some kind of bad conversion
happening between read and write, but not sure what.
Oh yeah, one other thing. I've tried just reading and immediately writing without changing anything
in the buffer and got the same results, so I'm fairly sure it's not in my conversion method.
After fighting with this whole problem for a while, I've tried using RandomAccessFile instead and reading in bytes. Haven't fully gotten that to work, but I'm hopeful. However, I'm still really curious as to why the aforementioned problem is happening. Thanks for any help.