Wednesday, May 25, 2016

Convert InputStream to String in Java

Sometimes in Java world it is necessary to convert an InputStream to a String for further processing. There are several ways to do it, but here is a fantastic trick I recently discovered in this article:
final String text = new Scanner(inputStream)
        .useDelimiter("\\A").next();
The idea behind this trick is regex \A. It matches the beginning of input. Since there is only one beginning of input the whole contents of the stream is returned as the first (and the last) token.

There is a problem with the code above. It would throw an exception if the provided stream is empty. However this is easy to fix:
final Scanner scanner = new Scanner(inputStream)
        .useDelimiter("\\A");
final String text = scanner.hasNext() ? scanner.next() : "";
If a specific charset must be used it could be passed as the second argument to the Scanner constructor:
final Scanner scanner = new Scanner(inputStream, "ISO-8859-1")
        .useDelimiter("\\A");
final String text = scanner.hasNext() ? scanner.next() : "";
That's all there is to it.
Thanks for reading!

9 comments:

  1. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    hadoop training in bangalore

    ReplyDelete
  2. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    R Programming Training in Chennai

    ReplyDelete
  3. I ‘d mention that most of us visitors are endowed to exist in a fabulous place with very many wonderful individuals with very helpful things.
    AWS Training in Bangalore

    ReplyDelete
  4. I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You.
    ME/M.Tech Project Center in Chennai | ME/M.Tech Project Center in Velachery

    ReplyDelete
  5. Awesome post. Really you are shared very informative concept.. Thank you for sharing. Keep on updating..
    Best Microsoft Azure Training Institute in Chennai | Best Microsoft Azure Training Institute in Velachery

    ReplyDelete
  6. I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.
    safety professional course in chennai

    ReplyDelete
  7. The information you shared is very effective for learners.

    Visit for a real time training for Java Training in Chennai | Best Java Training Institute in Chennai | Java Master Program Training in Chennai

    ReplyDelete
  8. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here
    fire and safety course in chennai

    ReplyDelete