Java InputStream到Java8流标记化

时间:2017-03-22 20:29:46

标签: java-8 tokenize java-io

有没有办法将文本文件中的每个单词作为字符串的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

1 个答案:

答案 0 :(得分:4)

假设你的单词用空格分隔:

    try (Stream<String> s = Files.lines(Paths.get("Your path"))
            .flatMap(Pattern.compile("\\s+")::splitAsStream)) {
        s.forEach(System.out::println);
    }