How to get a stream by lines of text at a specific url in Java 8?

I would like to read these words line by line: http://www.puzzlers.org/pub/wordlists/unixdict.txt

I tried to get Stream:

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 underlying file as well
stream.close();

but, as I suspected, it only works for files. Are there similar methods for urls?

+4
source share
2 answers

BufferedReaderalso has a method lines()that returns a stream. So you just need to open the BufferedReader, which wraps the InputStreamReader, wrapping the URL connection input stream:

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);
}
+12
source

Check this question: Read url for string in multiple lines of java code

Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();
0

Source: https://habr.com/ru/post/1615736/


All Articles