I recently started to learn Java and as I'm really the type of a person that learns much quicker with a task in hands I decided to take a small application written in C# and create an equivalent in Java.
Perhaps I should have start with smaller tasks, but since I already started to design it (the C# app is not written very well, hence creating an equivalent application in terms of features, not design and structure), I don't feel like dropping my idea.
Well, as you may probably realized by now, reading this, I am stuck. The application is kind of an editor that acts on data stored in a binary file. What I can't figure out at this time is how to read this file (one thing is reading) and parse (extract) data I need. I know the structure of this file. So here are the things I'm looking for:
- How should I access binary data stored in the file (in C# I would use BinaryReader)
- How to deal with primitives that are not available in Java (uint8_t, uint16_t, since the file is created in C++)
EDIT
I should have probably also mention that I probably need to load whole file into memory before processing! The file is 2MB.
I usually get lost when dealing with binary files and streams :x
EDIT 2
I think I figured it out in the meantime. I need to verify 4 byte signature at first. So I do this:
byte[] identifier = {'A', 'B', 'C', 'D'};
fs = new FileInputStream(filename);
byte[] extractedIdentifier = new byte[4];
if(4 != fs.read(extractedIdentifier)) {
throw new Exception();
}
if(!Arrays.equals(identifier, extractedIdentifier)) {
throw new Exception();
}
and after this I need whole file anyway, so I found MappedByteBuffer
https://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html which I think I will look into, because it seems like the perfect solution at first glance.
FileChannel fc = fs.getChannel();
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
Since I just started reading about this, are there any side effects of using this method? Is there a better way to do this?