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?
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With