38

I want to convert an InputStream is into a Stream<String> stream given a Charset cs in such a way that stream consists of the lines of is. Furthermore a line of is should not be read immediately but only in case stream needs it.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73
  • And what have you tried? Questions should show effort by including an attempt or research – Vince May 19 '15 at 21:14
  • 2
    Does it have to be `InputStream`? If you are going to read files then you could use `Files.lines(Path path, Charset cs)`. You can take a look at source code of this method to figure out your solution. – Pshemo May 19 '15 at 21:15
  • In my case it is the InputStream coming from `HttpURLConnection#getInputStream()`. – principal-ideal-domain May 19 '15 at 21:18
  • Okay, I did so. See http://stackoverflow.com/questions/30336889/convert-inputstream-into-streamstring-of-strings-of-fixed-length – principal-ideal-domain May 19 '15 at 21:59

1 Answers1

65

I think you can try:

Stream<String> lines = new BufferedReader(new InputStreamReader(is, cs)).lines();
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
  • Is there a way to auto disconnect the HttpURLConnection after the complete InputStream was read? – principal-ideal-domain May 19 '15 at 21:30
  • 1
    You can read the stream in a `try-with-resources` statement and possibly add a `finally` block that calls `disconnect()` on the `HttpURLConnection` object: http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#disconnect() – Costi Ciudatu May 19 '15 at 21:47
  • 2
    `try( BufferedReader br=new BufferedReader(new InputStreamReader(is, cs)); Stream lines=br.lines() ) { /* your stream operation */ }` will do. – Holger May 20 '15 at 08:35
  • 1
    In case you need more flexibility defining the pattern this is also nice: new Scanner(is).findAll() – Aleksander Lech Apr 18 '19 at 08:01
  • 1
    Apache Commons IO has an `AutoCloseInputStream` that automatically closes the stream when it reaches the end. You can then safely return this `Stream` without having to wrap it in a try-with-resources. e.g. `new BufferedReader(new InputStreamReader(new AutoCloseInputStream(is), cs)).lines()` (FYI @principal-ideal-domain, if you still need this info 7 years on...) – Jelaby May 18 '22 at 08:40
  • I don't like `BufferedReader`. Is there any way to make a `Path` object out of an inputstream (e.g. `System.in`) so that I can type something like `Files.lines(InputStreamPathObject, charset)`? – Sergey Zolotarev Feb 10 '23 at 17:17