Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FileOutputStream write(byte[] arg0) causes extra bytes???

Status
Not open for further replies.

vulcand4

Programmer
Jul 29, 2003
76
US
I am using a FileOutputStream to write binary (byte array) data to a file.

Right upon instanciation of the stream:
Code:
FileOutputStream fos = new FileOutputStream(new File("c:\\temp\\file.bin"))
I get 0xFFFE added to the front of the file. (before I even try to write to the stream).

Then when I do write using something like this:
Code:
byte[] b = "Hello there!".toBytes();
fos.write(b);

I get the data in my file, but if I view it in a hex editor, I see an extra 0x00 after each byte. This causes my file to be twice as large as it should and the binary data obviously isn't correct.

Any clues?
 
My documentation doesn't show a method String: toBytes (); I'm using jdk 1.5.0_04-b05 - is this something new?

Apart from that, I have the impression the conversion to byte-array is interpreting the String as UTF-16 encoded, which leads to 2-byte/char which would be obviously correct.

If you use a java-api, which replaces the class String, you should study their documentation carfully and mention your source/ api.

seeking a job as java-programmer in Berlin:
 
... I expect the String.getBytes() method was what was meant ?!

Incidentally, if you're writing text to a file, the java.io.FileWriter class is probably a better one to use than FileOutputStream. You'll get a method for writing a String to the file directly without having to extract a byte array first.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
Dian, I don't think it does you know - I'm sure it writes bytes, not ints (if it wrote ints, you'd be in terrible trouble).

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Arghh, sorry, I hate monday mornings.

That's the general contract for OutputStream, FileOutputStream should have overridden it ... or not ... which JVM are you using?

Cheers,
Dian

 
Yes timw, I did mean getBytes();

I ended up solving my problem by wrapping my FileOutputStream in an OutputStreamWriter - instanciated with a CHARSET of "ISO-8859-1". That kept it from producing a 2-byte unicode character.

Thanks a lot for all your input. You are a great knowledge base to work from. I'm hoping I can give some helpful input to an issue or two some day.

-PG
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top