有什么方法可以让这个过程简单一点吗?既然我需要每个条目的字节,有没有什么方法可以不使用ByteArrayOutputStream而获得它们
public UnzippedFile unzip(ZipFile zipFile) throws IOException {
var unzippedFile = new UnzippedFile();
try (ZipInputStream zipInputStream = ZipUtils.toZipInputStream(zipFile)) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
byte[] buffer = new byte[1024];
int len;
try (var file = new ByteArrayOutputStream(buffer.length)) {
while ((len = zipInputStream.read(buffer)) > 0) {
file.write(buffer, 0, len);
}
unzippedFile.addFileToMap(entry.getName(), file.toByteArray());
}
}
}
return unzippedFile;
}
我的UnzippedFile类:
public class UnzippedFile {
@Getter
private final Map<String, byte[]> filesMap;
public UnzippedFile() {
this.filesMap = new HashMap<>();
}
public void addFileToMap(String name, byte[] file) {
filesMap.put(name, file);
}
}
1条答案
按热度按时间jrcvhitl1#
如果您使用的是Java9+,那么您应该能够使用
readAllBytes()
简化代码。