Imagine that you have a method that requires an InputStream
, and you want to test that method. How can you test it?
In the Scala Cookbook I wrote how your Scala method can accept a Source instead of a File to make it easier to test, so I won’t write any more about that right now.
But if you have a method that accepts an InputStream
and you want to be able to test it with a String
, here’s what you can do:
// 1) create the desired String val s: String = "hello, world" // 2) convert that String to an InputStream val inputStream = new ByteArrayInputStream(s.getBytes)
The first line of code shown creates a String
object named s.
The second line of code does what you want, converting the string s into a ByteArrayInputStream
, which is a type of InputStream
. It calls the getBytes
method on the String
object, and uses that as a parameter to the ByteArrayInputStream
constructor. You can now pass the inputStream
object to any method that requires an InputStream
.
In summary, if you needed to see how to convert a Scala (or Java) String
to an InputStream
, I hope this has been helpful.