有没有办法将文本文件中的每个单词作为字符串的Java8流来获取?
E.g。你有test.txt:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
你得到了流:
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
Stream<String> s = br.lines();
发出一串文字(在空格处分开),你可以.forEach
打印吗?
Lorem
ipsum
dolor
sit
amet,
consectetur
adipiscing
elit,
sed
do
eiusmod
答案 0 :(得分:4)
假设你的单词用空格分隔:
try (Stream<String> s = Files.lines(Paths.get("Your path"))
.flatMap(Pattern.compile("\\s+")::splitAsStream)) {
s.forEach(System.out::println);
}