在開發遊戲時,總是要使用很多的資源檔案,比如:圖檔、音樂等。而我們經常會遇到一些商業遊戲中都看不到這些資源檔案,那是因為商業遊戲,一般都會将這些資源檔案打包成二進制的檔案,然後在程式中讀取,并使用。這樣的遊戲看上去更顯得專業一些,本文我們就來學習一個最簡單的将資源檔案打包成二進制檔案的方法——使用BinCompiler将資源檔案打包成二進制檔案。
所需工具:BinCompiler(見附件)
運作“BinCompiler.exe”,指定要打包的資源檔案的路徑,和輸出二進制檔案的路徑,如下圖所示。

- FName Index Pos Size
- A_04.png 0 0 4141
- A_03.png 1 4145 3802
- A_02.png 2 7951 3813
- A_01.png 3 11768 3959
接下來我們可以使用BinReader.java檔案中的兩個方法來讀取這些資源檔案了。
代碼清單:BinReader.java
- /*******************************************************************************
- * Reads a file from the BIN file and return data as a byte buffer
- *******************************************************************************/
- public byte[] readFile(String binfile, int pos)
- {
- byte buffer[];
- int len;
- try {
- InputStream is = Class.getClass().getResourceAsStream("/" + binfile);
- is.skip(pos);
- len = (is.read() & 0xFF) << 24;
- len |= (is.read() 0xFF) << 16;
- len |= (is.read() & 0xFF) << 8;
- len |= (is.read() & 0xFF);
- buffer = new byte[len];
- is.read(buffer, 0, buffer.length);
- is.close();
- is = null;
- System.gc();
- } catch (Exception e) {
- buffer = null;
- e.printStackTrace();
- return null;
- }
- return buffer;
- }
- * Reads a file from the BIN file and return data as an Image
- public Image readImage(String binfile, long pos)
- long len;
- len |= (is.read() &0xFF) << 16;
- len -= 4;
- return Image.createImage(buffer, 0, buffer.length);
- }
可以看出,這兩個方法都隻需要傳入bin檔案名和圖檔對應的pos,pos值就在我們上面所說的index.txt檔案中去找對應的就可以了。
- Image image = readimage("images.bin", 0);