如何以Java 8方式在特定URL上获取文本行?

Ala*_*ska 6 java java-8 java-stream

我想逐行阅读这些文字:http://www.puzzlers.org/pub/wordlists/unixdict.txt

我试图得到一个流:

Stream<String> stream = Files.lines(Paths.get("http://www.puzzlers.org/pub/wordlists/unixdict.txt"));
stream.forEach((word) -> System.out.println(word));
//Close the stream and it's underlying file as well
stream.close();
Run Code Online (Sandbox Code Playgroud)

但我怀疑它只适用于文件.是否有类似的URL方法?

JB *_*zet 14

BufferedReader还有一个lines()返回流的方法.所以你只需要打开一个包装了一个包含URL连接输入流的InputStreamReader的BufferedReader:

try (InputStream is = new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openConnection().getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
     Stream<String> stream = reader.lines()) {
    stream.forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)