Java - Use DataOutputStream and DataInputStream to process binary file

在這裡將說明如何利用Java DataOutputStream and DataInputStream來write and read binary file,若是利用Notepad++ 一般模式會得到如下的內容如圖一,字串雖可以正常顯示,但是其它binary content如int內容則是呈現猶如亂碼的資料,因此我們可以安裝Notepad++ plugin Hex View Editor來顯示十六進位的內容如圖二,但是十六進位的內容應該只有資訊人看得懂,但沒差我想正常人打開binary file所看到的圖一內容應該會以為檔案是否已經毀損了吧XDDD

圖一

圖二

在此說明一下資料內容的格式,如下:

byte[0x00-0x04]: 5 bytes,"START" String
byte[0x05-0x08]: 4 bytes,存放資料筆數為一Integer,如00 00 00 0a這四個byte資料,換算成十進位也就是10
byte[0x09-0x14]: 12 bytes,保留欄位
byte[0x15-0x??]: 以資料筆數來推算,在此為10筆,每筆皆為4 bytes的Integer數字,範圍為0x15-0x3c,共40 bytes
最後的3 bytes為"END" String,也是以資料筆數來推算,因此為0x3d-0x3f,共3 bytes

程式共分成兩個部分,先自行產生一random.bin的二進位檔案,接著再讀取該檔案的內容進行輸出的動作!
public static void main(String[] args) {
  // TODO Auto-generated method stub
  new ReadWriteBinaryFile();
}
 
public ReadWriteBinaryFile() {
  String file = "random.bin";
  try {
   writeBinaryFile(file);
   readBinaryFile(file);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
}

一、Write binary file
public void writeBinaryFile(String filename) throws IOException {
  int count = 10;
  int reserved = 12;
  DataOutputStream ostream = null;
  String sTag = "START";
  String eTag = "END";
  System.out.println("writeBinaryFile...");
  try {
    ostream = new DataOutputStream(new FileOutputStream(filename));
    ostream.write(sTag.getBytes());
    ostream.writeInt(count);
   
    System.out.println(sTag);
    for(int i = 0 ; i < reserved ; i++) {
       ostream.write(0xff);
    }
    Random rand = new Random();
    for(int i = 0 ; i < count ; i++) {
       int v = rand.nextInt(10);
       System.out.println(v);
       ostream.writeInt(v);
    }
    ostream.write(eTag.getBytes());
    System.out.println(eTag);
    ostream.flush();
  }finally {
    if(ostream != null) {
       ostream.close();
    }
  }
}

二、Read binary file
public void readBinaryFile(String filename) throws IOException {
  int count;
  byte[] sTag = new byte[5];
  byte[] eTag = new byte[3];
  byte[] reserved = new byte[12];
  DataInputStream istream = null;
  System.out.println("readBinaryFile...");
  try {
    istream = new DataInputStream(new FileInputStream(filename));
    istream.read(sTag);
    count = istream.readInt();
    istream.read(reserved);
   
    System.out.println(new String(sTag));
    for(int i = 0 ; i < count ; i++) {
       int v = istream.readInt();
       System.out.println(v);
    }
    istream.read(eTag);
    System.out.println(new String(eTag));
  }finally {
    if(istream != null) {
       istream.close();
    }
  }
}

Demo結果如下:

留言