• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Writing binary files in Java

Status
Not open for further replies.
Hi again; same topic, different language :p

Is there a good way to do this? An array of char[]'s seems awkward seeing as Java likes to do it's own wacky unicode thing.

What I'm writing right now is a method to write out some data I have to a TGA file. The fields in question here are two shorts representing the height and width of the image.

Here's the code snippet I'm using:

Code:
char[] header = new char[18];
...
header[12] = (char)(xSize%256);
header[13] = (char)(xSize/256);
header[14] = (char)(ySize%256);
header[15] = (char)(ySize/256);
...
FileWriter w = new FileWriter( f ); // f is a File object
w.write( header );

The problem I'm having here is that for any image size between 128 and 160, 63 is being written to the file instead of the correct value. Casting the header back to an int and printing it out gives the correct value- the incorrect value is ONLY being written to a file.

Anyone know how I can fix this? Is there a better way to handle writing binary files to begin with? Please help.

Thanks
 

Phoenix

Member
Two things-

1) You probably want to deal with Bytes and not chars when dealing with binary files.

2) Use Readers and Writers when dealing with character data (text files) and use InputStreams and OutputStreams when dealing with binary data (binary files).

If you get stuck with something like that you may want to hit

http://www.javaalmanac.com
 
Status
Not open for further replies.
Top Bottom