Reading an InputStream until regex matches

1,257 views
Skip to first unread message

Joe Barnes

unread,
Jan 17, 2013, 2:56:52 PM1/17/13
to scala...@googlegroups.com
I'm a long-time Java developer turned onto Scala recently.  I've stumbled across an interesting problem that I can't figure out how to solve without using a variable.  I'm curious if it is possible.

My code is communicating with a remote device that has a CLI.  Whenever I send a command, I need to read back all of the data from a java.io.InputStream for that socket until I see the prompt.  The prompt isn't a fixed string, so I would like to use a regex to know when I encounter it.  Note that the socket doesn't close, so I can't watch for the end of the stream.  I also can't watch for new lines, because the prompt isn't followed by a return.

Now, one of the devices I was communicating with DID put a newline at the end of the prompt, so this was a cinch in Scala.  I used a java.io.BufferedReader (named r) and this one liner did the job:
val responses = Stream.continually(r.readLine()).takeWhile(promptRegex.findFirstMatchIn(_).isEmpty)

Unfortunately my current device does not include a new line, so my call to readLine() never returns.  I know I could make a stream that calls the read() method to read the stream byte-by-byte, but I can't look for a single character to know when I've hit my prompt.

I know I could solve this with a var, but I'd love to avoid it.  I'm hopeful that there's a more functional way to solve this problem.

Thanks,
Joe

Daniel Sobral

unread,
Jan 17, 2013, 9:12:00 PM1/17/13
to Joe Barnes, scala-user
Actually, this is a great fit for Iteratees. I'm going to give a link to an explanation about Playframework iteratees, despite some people not liking them much, because I think this article will be easy to understand and apply to your context.

--
Daniel C. Sobral

I travel to the future all the time.

Raymond Tay

unread,
Jan 17, 2013, 9:58:50 PM1/17/13
to Daniel Sobral, Joe Barnes, scala-user
Thanks for sharing that blog - nice article by James Roper :) 

Joe Barnes

unread,
Jan 18, 2013, 5:40:16 PM1/18/13
to scala...@googlegroups.com, Joe Barnes
I've been reading about Iteratees today, and I have to agree that this is exactly what I'm looking for.  I will especially have good use for their composability.  Now to get my mind wrapped around the concept... :)

Thanks!
Joe
Reply all
Reply to author
Forward
0 new messages