2009/11/08

fortranで吐いたバイナリをjavaで読み込む

fortranにて
write(11) i
write(11) j
write(11) i+j, i*j
でバイナリを吐くとする.
fortranではバイナリファイルを吐くとき,write文の前後に4バイト分のヘッダとフッタが書き出されるようなのでそれを考慮すべし.



4バイトは32ビット整数と同じなのでヘッダとフッタのスキップをreadIntで代用.
little endianの場合は一旦ByteBufferに入れておいて,エンディアン変換をする.


import java.io.*;
import java.util.*;
import java.nio.*;


public class Test{
  public static void main( String[] args ){
    Test test=new Test();
    test.readBig("bin.big");
    System.out.println("");
    test.readLittle("bin.little");

  }

  public Test(){
  }

  FileInputStream fis;
  BufferedInputStream bis;
  DataInputStream dis;

  public void readLittle(String file) {
    try {
      fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);


      ByteBuffer bb = ByteBuffer.allocate(1024);
      bb.putInt(dis.readInt());
      bb.putInt(dis.readInt());//i
      bb.putInt(dis.readInt());

      bb.putInt(dis.readInt());
      bb.putInt(dis.readInt());//j
      bb.putInt(dis.readInt());

      bb.putInt(dis.readInt());
      bb.putInt(dis.readInt());//i+j
      bb.putInt(dis.readInt());//i*j
      bb.putInt(dis.readInt());

      bb.order(ByteOrder.LITTLE_ENDIAN);
      System.out.println(String.format("n1:%d",bb.getInt(4)));
      System.out.println(String.format("n2:%d",bb.getInt(16)));
      System.out.println(String.format("n3:%d",bb.getInt(28)));
      System.out.println(String.format("n4:%d",bb.getInt(32)));

    }
    catch ( IOException e ) {
    }
  }
  public void readBig(String file) {
    try {
      fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);



      dis.readInt();
      int i = dis.readInt();//i
      System.out.println(String.format("n: %d",i));
      dis.readInt();

      dis.readInt();
      i = dis.readInt();//j
      System.out.println(String.format("n: %d",i));
      dis.readInt();

      dis.readInt();
      i = dis.readInt();//i+j
      System.out.println(String.format("n: %d",i));
      i = dis.readInt();//i*j
      System.out.println(String.format("n: %d",i));
      dis.readInt();


      fis.close();
      bis.close();
      dis.close();
    }
    catch ( IOException e ) {
    }
  }
}

0 件のコメント: