Creating and Using Custom Binary File Formats in Java

Started by
12 comments, last by frob 2 years, 1 month ago

Alberth said:
If you don't know, chances are you invent a format that looks good on paper but it difficult or even impossible to implement.

Or the reverse, a format that is just a dump of what you happen to have in memory at the time which is completely brittle and breaks every time you think of something new.

I've worked on plenty of programs where that was exactly the case. Effectively C code in the format of:

ASSERT( file_size == sizeof mystruct);
size_t items_read = fread( the_thing, sizeof mystruct, 1, the_file);
ASSERT( items_read == 1);

There are a few scenarios where that is great, and in fact exactly the reason the C functions fread() and fwrite() take both a size and a count so you can read and write arrays. But when it comes to designing a robust format, that's coming at it in the wrong direction.

Advertisement

@undefined okay, would you be able to write an example in your favourite language that converts a random object in to a binary file format and reads it back in as an example?

Boss Fight, Boss Fight, Boss Fight!

I just did above, with fread(). Mirror the call with fwrite(). This works well for plain old data, but does not work for pointers or for many more advanced uses. There is no need for a “binary format” as the data is inherently in the format in memory.

Again, Java has built in serializing functions both in raw binary formats and XML, as described above with links to documentation and tutorials. The simple version is provided out of the box.

Basic reading and writing is a first semester programming topic at many schools, second semester at others. It is something that every student needs to learn. Links to the documentation have already been given. All that is left is the actual learning.

This topic is closed to new replies.

Advertisement