[英]How to add the first number of every row in a txt file to an array in Java
我有一個如下所示的 txt 文件:
1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6
如何將每行的第一個數字添加到數組中,這意味着數組應該包含:1 5 9 3 就是這樣。
文件“test.txt”必須位於您的項目文件夾中
public static void main(String[] args) {
printFirstLetters("test.txt");
}
private static void printFirstLetters(String fileName) {
try(Stream<String> stream = createStreamFromFile(fileName)) {
stream.filter(line -> !line.isEmpty())
.map(line -> line.charAt(0))
.forEach(System.out::println);
}
catch(IOException e) {
e.printStackTrace();
}
}
private static Stream<String> createStreamFromFile(String fileName) throws IOException {
return Files.lines(Path.of(fileName));
}
OUTPUT :
1
5
9
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.