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的二進位檔案,接著再讀取該檔案的內容進行輸出的動作!
  1. public static void main(String[] args) {
  2. // TODO Auto-generated method stub
  3. new ReadWriteBinaryFile();
  4. }
  5. public ReadWriteBinaryFile() {
  6. String file = "random.bin";
  7. try {
  8. writeBinaryFile(file);
  9. readBinaryFile(file);
  10. } catch (IOException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. }

一、Write binary file
  1. public void writeBinaryFile(String filename) throws IOException {
  2. int count = 10;
  3. int reserved = 12;
  4. DataOutputStream ostream = null;
  5. String sTag = "START";
  6. String eTag = "END";
  7. System.out.println("writeBinaryFile...");
  8. try {
  9. ostream = new DataOutputStream(new FileOutputStream(filename));
  10. ostream.write(sTag.getBytes());
  11. ostream.writeInt(count);
  12. System.out.println(sTag);
  13. for(int i = 0 ; i < reserved ; i++) {
  14. ostream.write(0xff);
  15. }
  16. Random rand = new Random();
  17. for(int i = 0 ; i < count ; i++) {
  18. int v = rand.nextInt(10);
  19. System.out.println(v);
  20. ostream.writeInt(v);
  21. }
  22. ostream.write(eTag.getBytes());
  23. System.out.println(eTag);
  24. ostream.flush();
  25. }finally {
  26. if(ostream != null) {
  27. ostream.close();
  28. }
  29. }
  30. }

二、Read binary file
  1. public void readBinaryFile(String filename) throws IOException {
  2. int count;
  3. byte[] sTag = new byte[5];
  4. byte[] eTag = new byte[3];
  5. byte[] reserved = new byte[12];
  6. DataInputStream istream = null;
  7. System.out.println("readBinaryFile...");
  8. try {
  9. istream = new DataInputStream(new FileInputStream(filename));
  10. istream.read(sTag);
  11. count = istream.readInt();
  12. istream.read(reserved);
  13. System.out.println(new String(sTag));
  14. for(int i = 0 ; i < count ; i++) {
  15. int v = istream.readInt();
  16. System.out.println(v);
  17. }
  18. istream.read(eTag);
  19. System.out.println(new String(eTag));
  20. }finally {
  21. if(istream != null) {
  22. istream.close();
  23. }
  24. }
  25. }

Demo結果如下:

留言