我有一个大的字符串内容,压缩为GZIP,并存储在数据库中的BLOB。在从DB中提取时,我能够从其中检索字符串,如下所示:
try (
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
BufferedInputStream bufis = new BufferedInputStream(new GZIPInputStream(bis));
ByteArrayOutputStream bos = new ByteArrayOutputStream()
) {
byte[] buf = new byte[4096];
int len;
while ((len = bufis.read(buf)) > 0) {
bos.write(buf, 0, len);
}
retval = bos.toString();
}我的问题是对于一些输入记录,我有这个BLOB太大,我必须要从BLOB的5-6行grep。我必须大量处理这些记录,这是在记录记忆中留下的痕迹。
是否有一种方法可以从GZIP中提取内容块,如果仅在初始部分中获得这些行,则可以丢弃所有剩馀块。
谢谢你提前帮忙。
发布于 2020-09-18 15:46:02
不要一次将所有字节从BLOB读入内存。阅读你的BLOB 作为InputStream。
使用BufferedReader一次读取和检查一行。
一个BufferedReader包着另一个阅读器。若要将解压缩InputStream转换为读取器,请使用InputStreamReader。指定正在解压缩的文本的字符集是非常重要的;您不希望依赖于您正在运行的任何计算机的默认字符集,因为它可能因运行位置不同而有所不同。
所以看起来是这样的:
List<String> matchingLines = new ArrayList<>();
String targetToMatch = "pankaj";
try (BufferedReader lines = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
blob.getBinaryStream()),
StandardCharsets.UTF_8))) {
String line;
while ((line = lines.readLine()) != null) {
if (line.contains(targetToMatch)) {
matchingLines.add(line);
}
}
}由于提到grep,您也可以使用正则表达式来匹配行,但出于性能原因,我更喜欢String.contains而不是正则表达式,除非您确实需要正则表达式。
List<String> matchingLines = new ArrayList<>();
Matcher matcher = Pattern.comple("(?i)pankaj.*ar").matcher("");
try (BufferedReader lines = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
blob.getBinaryStream()),
StandardCharsets.UTF_8))) {
String line;
while ((line = lines.readLine()) != null) {
if (matcher.reset(line).find()) {
matchingLines.add(line);
}
}
}https://stackoverflow.com/questions/63956011
复制相似问题