我有一个文本文件,其中包含大约 2,000,000 行的大量数据。使用以下代码片段浏览文件很容易,但这不是我需要的;-)
def f = new File("input.txt")
f.eachLine() {
// Some code here
}
我只需要从文件中读取特定范围的行。有没有办法像这样指定开始行和结束行(伪代码)?我想避免在选择范围之前使用 readLines() 将所有行加载到内存中。
// Read all lines from 4 to 48
def f = new File("input.txt")
def start = 4
def end = 48
f.eachLine(start, end) {
// Some code here
}
如果 Groovy 无法做到这一点,也欢迎使用任何 Java 解决方案:-)
干杯,
罗伯特
Java解决方案:
BufferedReader r = new BufferedReader(new FileReader(f));
String line;
for ( int ln = 0; (line = r.readLine()) != null && ln <= end; ln++ ) {
if ( ln >= start ) {
//Some code here
}
}
恶心吧?
不幸的是,除非你的行是固定长度的,否则你将无法跳到start
高效地执行第 3 行,因为每行可以任意长,因此需要读取所有数据。这并不排除nicer不过解决方案。
Java 8
认为值得更新以展示如何使用 Streams 有效地做到这一点:
int start = 5;
int end = 12;
Path file = Paths.get("/tmp/bigfile.txt");
try (Stream<String> lines = Files.lines(file)) {
lines.skip(start).limit(end-start).forEach(System.out::println);
}
因为 Streams 是惰性评估的,所以它只会读取直到并包含的行end
(加上它选择执行的任何内部缓冲)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)