Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Stream to String Java/Groovy

Tags:

java

groovy

I stole this snippet off the web. But it looks to be limited to 4096 bytes and is quite ugly IMO. Anyone know of a better approach? I'm actually using Groovy btw...

String streamToString(InputStream input) {         StringBuffer out = new StringBuffer();         byte[] b = new byte[4096];         for (int n; (n = input.read(b)) != -1;) {             out.append(new String(b, 0, n));         }         return out.toString();     } 

EDIT:

I found a better solution in Groovy:

InputStream exportTemplateStream = getClass().getClassLoader().getResourceAsStream("export.template") assert exportTemplateStream: "[export.template stream] resource not found" String exportTemplate = exportTemplateStream.text 
like image 394
phil swenson Avatar asked Apr 29 '11 20:04

phil swenson


People also ask

Can we use stream in groovy?

Groovy 2.5. 0 adds several methods to make working with Java 8 Streams more Groovy. First of all the methods toList and toSet are added to the Stream class. These methods will convert the stream to a List and Set using the Stream.

How do you convert an InputStream into string in java?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.

Can we convert string to stream in java?

We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class.


1 Answers

Some good and fast answers. However I think the best one is Groovy has added a "getText" method to InputStream. So all I had to do was stream.text. And good call on the 4096 comment.

like image 168
phil swenson Avatar answered Sep 21 '22 11:09

phil swenson