Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get stream over lines of text at certain URL in Java 8 way?

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

I tried to get a 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's underlying file as well
stream.close();

but as I suspected it works only for files. Is there similar methods for URLs?

like image 685
Ala Kotowska Avatar asked Nov 13 '15 10:11

Ala Kotowska


People also ask

What is openStream () in Java?

The openStream() method returns a java.io.InputStream object so you can read from a URL using the normal InputStream methods. Input and Output Streams. describes the I/O classes provided by the Java development environment and shows you how to use them. Reading from a URL is as easy as reading from an input stream.

What are the methods in streams in Java 8?

With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.


1 Answers

BufferedReader also has a lines() method returning a stream. So you just need to open a BufferedReader wrapping an 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);
}
like image 158
JB Nizet Avatar answered Oct 31 '22 04:10

JB Nizet