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!