我正在从压缩的输入流中读取行,并且我需要根据前4个位置(一个句点)对其进行过滤。是否可以使用lambda (就像streams中的过滤器)来避免这种情况?
private List<String> readlinesByPeriod(DPeriod period, ZipInputStream zis) throws IOException {
List<String> lines = new ArrayList();
byte[] data = SCIOUtils.readData(zis);
InputStream is = new ByteArrayInputStream(data);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, CharEncoding.ISO_8859_1));
String line;
while ((line = reader.readLine()) != null) {
String periodCode = StringUtils.substring(line, 0, 4);
if (periodCode.equals(period.getCode())) {
lines.add(line);
}
}
return lines;
}发布于 2021-11-25 12:05:27
是的,这是可能的
return reader.lines()
.filter(line -> StringUtils.substring(line, 0, 4).equals(period.getCode()))
.collect(Collectors.toList());值得注意的是,the JavaDoc for BufferedReader.lines说
如果在访问基础BufferedReader时引发IOException,则将其包装在UncheckedIOException中,该an将从导致发生读取的流方法中引发
因此,如果您希望您的方法继续抛出已检查的异常(IOException或其他),则必须将上述内容包装在UncheckedIOException的try-catch块中,并将其包装并作为已检查的异常重新抛出。
https://stackoverflow.com/questions/70110700
复制相似问题