此代码读取我的txt文件的内容。我希望我的代码只读取前10行。
public void loadDataFromTxt() {
String fileName = "/Users/pietrzakadrian/Desktop/file.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:8)
您可以使用Stream#limit
方法:
String fileName = "/Users/pietrzakadrian/Desktop/file.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.limit(10).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
示例流:
Stream.of(5,4,3,1)
.limit(2)
.forEach(System.out::println);
输出:
5
4