簡體   English   中英

如何使用JAVA讀取C / Matlab創建的二進制文件

[英]How to read binary file created by C/Matlab using JAVA

我使用以下matlab代碼創建了一個二進制文件:

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循環后終止,但結果不正確。 任何人都可以幫助我。 非常感謝!

正如我猜測它是一個字節序問題,即你的二進制文件被寫成小端整數(可能是因為你使用的是英特爾或類似的CPU)。

但是,Java代碼正在讀取大端整數,無論​​它運行的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();
  }
}

如果您不想“手動”更改字節順序,請參閱此問題的答案:
將小Endian文件轉換為大Endian文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM