假设我有一个巨大的文件,我想每行读取 100 行并执行一项操作。 (我想合并 100 行并发送休息请求)
在 Java 7 中,我会执行如下操作。
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
int count = 0;
List<String> list = new ArrayList<>();
while ((line = br.readLine()) != null) {
list.add(line);
count++;
if (count % 100 == 0) {
//do the operation on list
list = new ArrayList();
}
}
} catch (IOException e) {
e.printStackTrace();
}
我们可以在这里利用 Java 8 Stream 吗? 我知道我们可以做这样的事情,但它在每一行而不是 100 行上运行。所以我认为 foreach 不是这里的选择。
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
最佳答案
如果您不喜欢上述方法,您可以简单地使用第二种方法,但您无法并行创建部分流,因为您必须按顺序读取行
。例如:
split(Paths.get("file"), 100).forEach(this::sendRequest);
void sendRequest(List<String> each) {
// then you must send the rest request in parallel here
}
<小时/>
Stream<List<String>> split(Path path, int limit) throws IOException {
// skip the remaining lines if its size < limit
return split(Files.lines(path), limit, true);
}
<T> Stream<List<T>> split(Stream<T> source,
int limit, boolean skipRemainingElements) {
//variables just for printing purpose
Spliterator<T> it = source.spliterator();
long size = it.estimateSize();
int c = it.characteristics();// characteristics
return stream(new AbstractSpliterator<List<T>>(size, c) {
private int thresholds = skipRemainingElements ? limit : 1;
@Override
@SuppressWarnings("StatementWithEmptyBody")
public boolean tryAdvance(Consumer<? super List<T>> action) {
List<T> each = new ArrayList<>(limit);
while (each.size() < limit && it.tryAdvance(each::add)) ;
if (each.size() < thresholds) return false;
action.accept(each);
return true;
}
}, false).onClose(source::close);
}
关于lambda - Java 8 Stream 每 100 行读取一次文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935165/