转载于此
本功能所涉及到的原理在上述文章中已有阐述, 这里主要是将实现代码贴出来
向apk文件中写入Comment的代码段
public static void setZipComment(String filePath, String comment) { File file = new File(filePath); ZipFile zipFile = null; ByteArrayOutputStream outputStream = null; RandomAccessFile accessFile = null; try { zipFile = new ZipFile(file); outputStream = new ByteArrayOutputStream(); byte[] byteComment = comment.getBytes(); outputStream.write(byteComment); outputStream.write(short2Stream((short) byteComment.length)); byte[] data = outputStream.toByteArray(); accessFile = new RandomAccessFile(file, "rw"); accessFile.seek(file.length() - 2); accessFile.write(short2Stream((short) data.length)); accessFile.write(data); } catch (IOException e) { e.printStackTrace(); } finally { try { if (zipFile != null) { zipFile.close(); } if (outputStream != null) { outputStream.close(); } if (accessFile != null) { accessFile.close(); } } catch (Exception e) { } } } public static byte[] short2Stream(short data) { ByteBuffer buffer = ByteBuffer.allocate(2); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort(data); buffer.flip(); return buffer.array(); }
在apk源代码中读取写入的Comment
public static String getZipComment(String filePath) { File file = new File(filePath); byte[] bytes; RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r"); long index = randomAccessFile.length(); bytes = new byte[2]; index = index - bytes.length; randomAccessFile.seek(index); randomAccessFile.readFully(bytes); bytes = new byte[stream2Short(bytes, 0)]; index = index - bytes.length; randomAccessFile.seek(index); randomAccessFile.readFully(bytes); return new String(bytes, "utf-8"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { e.printStackTrace(); } } } return ""; } public static short stream2Short(byte[] stream, int offset) { ByteBuffer buffer = ByteBuffer.allocate(2); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(stream[offset]); buffer.put(stream[offset + 1]); return buffer.getShort(0); }
使用如下代码调用getZipComment即可获得写入的注释
Context#getPackageCodePath()
- 使用方法java -jar zip-comment.jar app-release.apk markets.txt
- zip-comment.jar 是代码生成的可执行jar
- app-release.apk是待多渠道的原始包
- markets.txt 是各个渠道代码, 尽量简短