从文件 Java 8 中读取行并在两者之间中断的最佳方法

Best way to read lines from file Java 8 and break in between

Files.lines().forEach() 方法不允许 break。以块的形式读取 Java 8 中的行并在需要时中断的最佳方法是什么?

更新 1:异常示例。

public class Main {
public static void main(String[] args) {

    try(IntStream s = IntStream.range(0, 5);){
    s.forEach(i -> validate(i));

    }catch(Exception ex){
    System.out.println("Hello World!");    
    }
}
static void validate(int s){

    if(s > 1){            
        //throw new Exception(); ?
    }
    System.out.println(s);
} }

这很容易通过使用 java-9 takeWhile,所以当条件 (s < 1) 失败时它将丢弃流的剩余部分 here

when an element is encountered that does not match the predicate, the rest of the stream is discarded.

s.takeWhile(s -> s < 1).forEach(System.out::println);

通过使用 java-8 尝试了一个示例,但这并不是每个都像 takeWhile 一样有效,通过组合 peekfindFirst() 但需要双重检查条件没有意义而不是这个我会更喜欢标准的 while 循环

IntStream.range(0, 5).peek(i->{
         if(i<3) {
             System.out.println(i);
         }

     }).filter(j->j>=3).findFirst();

findFirst

中验证谓词时,在 peek 和流中执行操作将中断