Friday, January 25, 2013

Stupid scanner tricks

This is a great piece of code I found here and it's so useful that I decided to write a post for it.
If you need to convert a stream to a String you can use this simple line of code:
 String text = new Scanner(new InputStream()).useDelimiter("\\A").next();  
Remember that Scanner takes in input any class implementing Readable: InputStream, File, Channel and so on. For example, if you need to fetch a big InputStream in a Servlet you can do it without using any loop. Also remember that regex "\A" matches the beginning of the input, and since there is only one begin in one input, Scanner will fetch the whole stream in one move! If you need a specific charset, you can specify it as a second parameter in Scanner constructor.

Good coding!

1 comment:

  1. I appreciate this blog to share knowledge about this important topic. Here I found different segments and now I am going to use these new tips with new enthusiasm. เครื่องสแกนเอกสาร

    ReplyDelete