我有一个下一个格式的文本文件:每一行都以字符串开头,后面跟着数字序列。每行有未知长度(未知数量,数量从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
。 它阻塞了吗? - 拆分与正则表达式的每一行
- 将每个行成头字符串,并设置数字
我认为这是非常uneffective由于第二和第三个步骤。第一步意味着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这种方法之外,我认为你不需要为每一行编译相同的模式。 – eg04lt3r