2011-10-12 55 views
4

我曾嘗試使用下面的MATLAB代碼創建一個二進制文件的C/Matlab的創建的二進制文件:如何讀取使用JAVA

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); 

我可以使用下面的C代碼讀取此文件:

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; 
} 
...... 

上面的C代碼可以讀取正確的結果。不過,我現在想在JAVA中讀取這樣的二進制文件。我的代碼如下所示:

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(); 

它會在n + 1循環後終止,但結果不正確。有人能幫助我嗎?非常感謝!

+1

怎麼結果不正確?例如,你的'System.out.println(...)'給出的'n'的值是什麼? –

+4

只是第一次猜測:也許這是一個排序問題 – Curd

+0

我也在考慮@ Curd的線路。如果您已經解決了問題,請隨時自行發佈答案,因爲這可能對其他人有用。 –

回答

4

正如我猜測這是一個排序問題,即 您的二進制文件被寫爲小端編碼 (可能是因爲您使用的是英特爾或類似的CPU)。

但是,Java代碼正在讀取big-endian整數,無論​​它運行在哪個CPU上。

爲了顯示問題,以下代碼將讀取您的數據並在字節序轉換前後顯示整數作爲十六進制數。

import java.io.*; 

class TestBinaryFileReading { 

    static public void main(String[] args) throws IOException { 
    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.printf("%08X ",t); 

     // change endianness "manually": 
     t = (0x000000ff & (t>>24)) | 
      (0x0000ff00 & (t>> 8)) | 
      (0x00ff0000 & (t<< 8)) | 
      (0xff000000 & (t<<24)); 
     System.out.printf("%08X",t); 
     System.out.println(); 
     } 
     catch (java.io.EOFException eof) { 
     break; 
     } 
    } 
    data_in.close(); 
    } 
} 

如果你不想做的更改端「手動」,看到回答這個問題 :
convert little Endian file into big Endian