7

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?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Ala Kotowska
  • 71
  • 1
  • 2

2 Answers2

16

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);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Check this question out: Read url to string in few lines of java code

This answer seems the most appropriate

Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();
Community
  • 1
  • 1
bruno_cw
  • 994
  • 1
  • 8
  • 22