public static final int DEFAULT_SIZE = 1024 * 1024 *2; public static void main(String... args) {
byte[] signature = new byte[]{0x50,0x4b,0x01,0x02}; String filename = "./test.apk"; File file = new File( filename);
try { RandomAccessFile accessFile = new RandomAccessFile(file,"r"); RandomAccessFile accessFile2 = new RandomAccessFile(file,"r"); long offset = file.length() - DEFAULT_SIZE; accessFile.seek(offset); byte[] buffer = new byte[1024]; int len = 0; while((len = accessFile.read(buffer) )> 0){ int index = 0; for (; index < len; index++) { boolean flag = true;
for (byte signatureB : signature) {
byte b = 0; if (index < buffer.length - 4){ b = buffer[index++]; }else{ b = (byte)accessFile.read(); } if (signatureB != b){ flag = false; break; } } //匹配到了0x02014b50标记 if (flag){
long subOffset = 0; if (index < buffer.length - 4){ subOffset = accessFile.getFilePointer() - buffer.length + index -4; }else{ subOffset = accessFile.getFilePointer(); } //0x04034B50 System.out.println("中心目录文件开始-----------" + subOffset); System.out.println("offset =" + subOffset); //压缩后文件大小 4字节 accessFile2.seek(subOffset + 20); int fileSize = 0; for (int i =0; i < 4; i++) { fileSize += (accessFile2.read()<< (8 *i)); } accessFile2.skipBytes(4); //文件名大小 2字节 int size_byte1 = accessFile2.read(); int size_byte2 = accessFile2.read();
if (nameString.contains("AndroidManifest.xml")){ // file header accessFile2.seek(fileOffset);
FileOutputStream out = new FileOutputStream("./dest.xml"); // 文件里还有一个小文件头,这里加了1024字节,实际情况很小 byte[] buf = new byte[fileSize + 1024]; accessFile2.read(buf); ByteArrayInputStream bInputStream = new ByteArrayInputStream(buf); ZipInputStream zin = new ZipInputStream(bInputStream);