Modifies only the specified entries in a zip file. @param input a source from a zip file @param output an output to a zip file @param toModify a map from path to an input stream for the entries you'd like to change @param toOmit a set of entries you'd like to leave out of the zip @throws IOExc
(ByteSource input, ByteSink output, Map<String, Function<byte[], byte[]>> toModify, Predicate<String> toOmit)
| 98 | * @throws IOException |
| 99 | */ |
| 100 | public static void modify(ByteSource input, ByteSink output, Map<String, Function<byte[], byte[]>> toModify, Predicate<String> toOmit) throws IOException { |
| 101 | try (ZipInputStream zipInput = new ZipInputStream(input.openBufferedStream()); |
| 102 | ZipOutputStream zipOutput = new ZipOutputStream(output.openBufferedStream())) { |
| 103 | while (true) { |
| 104 | // read the next entry |
| 105 | ZipEntry entry = zipInput.getNextEntry(); |
| 106 | if (entry == null) { |
| 107 | break; |
| 108 | } |
| 109 | |
| 110 | Function<byte[], byte[]> replacement = toModify.get(entry.getName()); |
| 111 | if (replacement != null) { |
| 112 | byte[] clean = ByteStreams.toByteArray(zipInput); |
| 113 | byte[] modified = replacement.apply(clean); |
| 114 | // if it's the entry being modified, enter the modified stuff |
| 115 | try (InputStream replacementStream = new ByteArrayInputStream(modified)) { |
| 116 | ZipEntry newEntry = new ZipEntry(entry.getName()); |
| 117 | newEntry.setComment(entry.getComment()); |
| 118 | newEntry.setExtra(entry.getExtra()); |
| 119 | newEntry.setMethod(entry.getMethod()); |
| 120 | newEntry.setTime(entry.getTime()); |
| 121 | |
| 122 | zipOutput.putNextEntry(newEntry); |
| 123 | copy(replacementStream, zipOutput); |
| 124 | } |
| 125 | } else if (!toOmit.test(entry.getName())) { |
| 126 | // if it isn't being modified, just copy the file stream straight-up |
| 127 | ZipEntry newEntry = new ZipEntry(entry); |
| 128 | newEntry.setCompressedSize(-1); |
| 129 | zipOutput.putNextEntry(newEntry); |
| 130 | copy(zipInput, zipOutput); |
| 131 | } |
| 132 | |
| 133 | // close the entries |
| 134 | zipInput.closeEntry(); |
| 135 | zipOutput.closeEntry(); |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /** Modifies a file in-place. */ |
| 141 | public static void modify(File file, Map<String, Function<byte[], byte[]>> toModify, Predicate<String> toOmit) throws IOException { |