我正在尝试解压缩一个装满JSON文件的巨大zip文件(多个GB)。我只想保留包含标签foo=1
的文件。
我尝试使用unzip
命令解压缩整个内容,然后处理数据,但是存在存储限制。我正在尝试查看是否有一种方法可以同时解压缩这些文件,并且
foo=1
,请删除文件我不找到一种方法来完成整个过程。有人有什么想法吗?
理想情况下,这将是一个bash命令,但是如果有一种用Java实现的方法,我也将不胜感激
谢谢!
答案 0 :(得分:1)
通过java
,您可以这样做
public void unzipFile(String zip, String dest) throws Exception {
String fileZip = Paths.get(zip).toString();
File destDir = Paths.get(dest).toFile();
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = Paths.get(destDir.getAbsolutePath(), zipEntry.getName()).toFile();
FileOutputStream fos = new FileOutputStream(newFile);
// read the contents of the file
StringBuilder fileContents = readAllFileContents(zis);
// test if the contents are valid
if (isValid(fileContents)) {
fos.write(fileContents.toString().getBytes());
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private boolean isValid(StringBuilder fileContents) {
return fileContents.toString().contains("foo=1");
}
private StringBuilder readAllFileContents(ZipInputStream zis) throws IOException {
byte[] buffer = new byte[1 << 10];
int len;
StringBuilder sb = new StringBuilder();
while ((len = zis.read(buffer)) > 0) {
sb.append(new String(buffer, 0, len));
}
return sb;
}