/* * * 读取已知格式的打包文件,通过文件头标志来拆分文件 * */ import java.io.*; public class write { protected static byte[] strbyte = null; public static StringBuffer sb = new StringBuffer(); public static void main(String[] args) throws Exception { FileInputStream in = new FileInputStream("e:/split/data_2.pak"); DataInputStream din = new DataInputStream(in); // 文件数据 int length = din.available(); byte[] data = new byte[length]; // 读取文件到字节数组 din.read(data); int startPos = 0; int endPos = 0; for (int j = 0; j < data.length; j++) { String tmp = Integer.toHexString(0xFF & data[j]).toUpperCase(); if (tmp.length() < 2) { for (int i = tmp.length(); i < 2; i++) tmp = "0" + tmp; } sb.append(tmp); //为操作方便转换成16进制后判断一下是否是PNG文件头标志 if (sb.toString().endsWith("89504E470D0A1A0A0000000D49484452")) { sb.delete(0,sb.length()); if (j - 15 > 0) { endPos = j - 15; // 生成图片文件 fileCreate(startPos,endPos,data); startPos = j - 15; } } } din.close(); } public static void fileCreate(int startPos, int endPos, byte[] data) throws IOException { String pngFilePathName = "e:/split/img2/img_"+endPos+".png"; FileOutputStream out = new FileOutputStream(pngFilePathName); BufferedOutputStream buffout = new BufferedOutputStream(out); DataOutputStream dataout = new DataOutputStream(buffout); for (int j = startPos; j < endPos; j++) { dataout.write(data[j]); } dataout.close(); System.out.println(pngFilePathName); } }