我正在尝试将数据添加到zip文件头字段。特别是使用java进入zip头中指定的额外字段。可能吗 ?
public class test {
public static void main(String[] args) {
String path = "finalName.zip";
RandomAccessFile file = null;
try {
file = new RandomAccessFile(path, "rw");
byte[] buf = new byte[(int) file.length() / 1024];
file.read(buf);
byte[] newHeader = "NEW DATA".getBytes();
System.out.println("Original zip : " + bytesToHex(buf));
System.out.println("newHeader : " + bytesToHex(newHeader));
int length = newHeader.length;
buf[28] = (byte) length;
byte[] firstPart = Arrays.copyOf(buf, 30);
byte[] endPart = Arrays.copyOfRange(buf, 30, buf.length );
System.out.println("firstPart zip original : " + bytesToHex(firstPart));
System.out.println("endPart zip original : " + bytesToHex(endPart));
byte[] firstPartAndHeader = new byte[30 + length];
System.arraycopy(firstPart, 0, firstPartAndHeader, 0, firstPart.length);
System.arraycopy(newHeader, 0, firstPartAndHeader, firstPart.length, newHeader.length);
System.out.println("firstPartAndHeader zip original : " + bytesToHex(firstPartAndHeader));
byte[] combined = new byte[firstPartAndHeader.length + endPart.length];
System.arraycopy(firstPartAndHeader, 0, combined, 0, firstPartAndHeader.length);
System.arraycopy(endPart, 0, combined, firstPartAndHeader.length, endPart.length);
System.out.println("combined zip original : " + bytesToHex(combined));
file.seek(0);
file.write(combined);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
我的方式是破坏文件。我在字节28中添加了额外标头的长度,在字节30中添加了额外的标头。还有什么需要做的吗?