6

Given a string:

String xml = "<test/>";

How do I convert it to an InputStream in Groovy?

Currently I use:

IOUtils.toInputStream(xml, StandardCharsets.UTF_8)

It works, but I'm looking for some shorter and dependency-free way of doing that in Groovy.

Of course I know answer for Java, but it involves ugly creation of ByteArrayInputStream. I'm looking for GDK way of solving that.

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • 1
    Possible duplicate of [How do I convert a String to an InputStream in Java?](https://stackoverflow.com/questions/782178/how-do-i-convert-a-string-to-an-inputstream-in-java) – Szymon Stepniak May 24 '18 at 11:47
  • 2
    `IOUtils.toInputStream()` does exactly `new ByteArrayInputStream()` stuff. GDK does not add any method similar to `InputStream.getText()` that converts String to InputStream. Actually doing it with `ByteArrayInputStream` is the easiest and straightest way. – Szymon Stepniak May 24 '18 at 11:52

2 Answers2

15

Has not much to do with Groovy, plain java:

InputStream stream = new ByteArrayInputStream( xml.getBytes( 'UTF-8' ) )
injecteer
  • 20,038
  • 4
  • 45
  • 89
  • 3
    Groovy has `text` method to convert `InputStream` to `String`, so I'm looking for similar shorthand the other way round without `ByteArrayInputStream`. – Michal Kordas May 24 '18 at 11:52
1

If you have org.apache.tools.ant.types.resources.StringResource on classpath it becomes just:

new StringResource(xml).inputStream

It is included in cglib, so if you do mocking, probably you can use above shorthand in tests.

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103