Tuesday 21 July 2009

Java/Matlab read and write 16-bit data file

  • Read 16 bit binary file:
    File file = new File("FILENAME.bin");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream( bis );

    short[] myarray = new short[256000];
    int cnt;
    for (cnt = 0; cnt < 256000; cnt++) {

    myarray[cnt] = dis.readShort();

    }
    fis.close();

    Alternatively:
    RandomAccessFile dis = new RandomAccessFile(new File("FILENAME.bin"), "r");

    Note:
    1) bufferedInputStream can be ignored, but it will improve the performance 90% for large file operation.
    2) RandomAccessFile works like a 'pointer', similar to fread in Matlab, offset or skip can be assign when data retrieving while not really load all the file. This class has both read and write methods, it is a convenience class, like filereader and filewriter, while the former method is kinda low level methods.

  • Write 16 bit binary file:
    FileOutputStream fos = new FileOutputStream(new File("OUTPUT.bin"));
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    DataOutputStream dos = new DataOutputStream(bos);

    for (cnt = 0; cnt < 256000; cnt++) {

    myarray[cnt] = dis.readShort();

    }

    bos.flush();

    fos.close();

    Alternatively:
    RandomAccessFile dos = new RandomAccessFile(new File("OUTPUT.bin"), "rw");
    Note: The following step is essential!!!! Otherwise, there will be some data lost.
    bos.flush();
  • Matlab:

    fid1 = fopen('filename.bin', 'r');
    A = fread(fid1, 100, 'uint16=>float32');
    fclose(fid1);

    fid2 = fopen('output.bin', 'w');
    fwrite(fid2, A, 'uint16');
    fclose(fid2);

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter