Re: Read binary data file
On Aug 29, 3:52 pm, Windsor.Lo...@gmail.com wrote:
I am a C++ programmer, working on a java program. I need to read a
binary file using Java.
Here is how I read it in C++,
Struct SOME_DATA
{
unsigned long data1;
unsigned short data2;
unsigned short data3;
unsigned long data4;
}
struct SOME_DATA someData;
and read using
fread(&someData, 12, 1, inputFile);
Please give me some pointers, how do i read this using Java? Thanks.
BTW, those are not the variable names I use in my program.
It's never a good idea portability-wise to write structs in binary
format (e.g. how do you deal with packing, different CPU
architectures, etc.?), but ignoring that for now you could naively do
something like the following. Note that this only works on big-endian
machines, and is probably unreliable there anyway.
jc@soyuz:~/tmp/binrw$ cat main.cpp
#include <stdio.h>
int main(int /*argc*/, char **argv) {
struct SOME_DATA {
unsigned long data1 ;
unsigned short data2 ;
unsigned short data3 ;
unsigned long data4 ;
} ;
SOME_DATA someData = { 1, 2, 3, 4 } ;
FILE *fh = fopen(argv[1], "wb") ;
fwrite(&someData, sizeof(someData), 1, fh) ;
fclose(fh) ;
return 0 ;
}
jc@soyuz:~/tmp/binrw$ g++ -W -Wall -pedantic -o test main.cpp
jc@soyuz:~/tmp/binrw$ ./test test2.file
jc@soyuz:~/tmp/binrw$ cat test.java
public class test {
public static void main(String [] args)
throws java.io.IOException {
java.io.DataInputStream dis
= new java.io.DataInputStream(
new java.io.FileInputStream(
new java.io.File(
args[0]
)
)
) ;
System.out.println("data1: " + dis.readInt()) ;
System.out.println("data2: " + dis.readShort()) ;
System.out.println("data3: " + dis.readShort()) ;
System.out.println("data4: " + dis.readInt()) ;
}
}
jc@soyuz:~/tmp/binrw$ javac test.java
jc@soyuz:~/tmp/binrw$ java -classpath . test test2.file
data1: 1
data2: 2
data3: 3
data4: 4
For reference, duplicating the above on an Intel box yields:
jc@jc-ubuntu:~/tmp/binrw$ java test test.file
data1: 16777216
data2: 512
data3: 768
data4: 67108864