java - 有没有办法在解压文件的同时检查当前正在解压的文件?
问题描述
我正在尝试解压缩一个包含 JSON 文件的巨大 zip 文件(多个 GB)。我只想保留包含标签的文件foo=1
。
我尝试使用unzip
命令解压缩整个内容,然后处理数据,但存在存储限制。我正在尝试查看是否有办法同时解压缩这些文件,并且
- 检查正在解压缩的每个文件
- 如果文件不包含
foo=1
,删除文件 - 对所有文件重复
如果不解压缩整个东西,我找不到一种方法。有没有人有任何想法?
理想情况下,这将是一个 bash 命令,但如果有办法在 java 中做到这一点,我也将不胜感激
谢谢!
解决方案
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;
}
推荐阅读
- botframework - 如何让机器人只向某些人发送消息
- google-cloud-platform - 获取使用资源的服务帐户
- python - 预填充 Flask SQLAlchemy 数据库
- swift - 在一个字符串中多次使用 NSAttributedString
- azure-application-gateway - Restrict access of the back-end pool form application gateway public ip
- python - 当我在文件中写入元组时,我在控制台中打印时丢失了一些值,我得到了所有值
- wso2 - SourceHandler Writer 调用informWriterError 时为null,无法工作
- java - Project Reactor,在创建 lambda 之外使用 Flux sink
- excel - 我想在不使用 sendkeys 的情况下自动化 F2+Enter。我从单词表中提取的文本没有任何作用
- solr - 使用版本号更新 SOLR 模式