【发布时间】:2017-03-06 18:01:41
【问题描述】:
我有一个下一个格式的文本文件:每一行都以一个字符串开头,后面跟着一个数字序列。每行的长度未知(数字数量未知,数量从 0 到 1000)。
string_1 3 90 12 0 3
string_2 49 0 12 94 13 8 38 1 95 3
.......
string_n 9 43
之后我必须使用handleLine 方法处理每一行,该方法接受两个参数:字符串名称和数字集(参见下面的代码)。
如何有效地读取文件并使用handleLine 处理每一行?
我的解决方法:
- 使用java8流
Files.lines逐行读取文件。 它会阻塞吗? - 用正则表达式分割每一行
- 将每一行转换为标题字符串和一组数字
我认为由于第 2 步和第 3 步,它非常无效。第一步意味着java首先将文件字节转换为字符串,然后在第二步和第三步中将它们转换回String/Set<Integer>。 这对性能有很大影响吗?如果是 - 如何做得更好?
public handleFile(String filePath) {
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(this::indexLine);
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleLine(String line) {
List<String> resultList = this.parse(line);
String string_i = resultList.remove(0);
Set<Integer> numbers = resultList.stream().map(Integer::valueOf).collect(Collectors.toSet());
handleLine(string_i, numbers); // Here is te final computation which must to be done only with string_i & numbers arguments
}
private List<String> parse(String str) {
List<String> output = new LinkedList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
【问题讨论】:
-
正如建议,也许将 Pattern.compile 移到此方法之外,我认为您不需要为每一行编译相同的模式。