I created a binary using the following matlab code:
x is an array of int32 numbers n is the length of x fid = fopen("binary_file.dat", "wb"); fwrite(fid, n, 'int32'); fwrite(fid, x, 'int32'); fclose(fid);
I can use the following C code to read this file:
fp = fopen("binary_file.dat", "rb"); int n; fread(&n, 4, 1, fp);//read 4 bytes int *x = new int[n]; for (int i = 0; i < n; i++) { int t; fread(&t,4, 1,fp);//read 4 bytes x[i] = t; } ......
The above C code can read the correct results. However, now I want to read such a binary in JAVA. My code is displayed as follows:
DataInputStream data_in = new DataInputStream( new BufferedInputStream( new FileInputStream( new File("binary_file.dat")))); while(true) { try { int t = data_in.readInt();//read 4 bytes System.out.println(t); } catch (EOFException eof) { break; } } data_in.close();
It ends after n + 1 cycles, but the results are incorrect. Can someone help me. Many thanks!
java c binary matlab
skyuuka
source share