What is the resource efficient way to generate inputstream?

Viewed 60

I am new to Java IO. Currently, I have these lines of code which generates an input stream based on string.

String sb = new StringBuilder();
for(...){
   sb.append(...);
}
String finalString = sb.toString();
byte[] objectBytes = finalString.getBytes(StandardCharsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(objectBytes);

Maybe, I am misunderstanding something, but is there a better way to generate InputStream from String other than using getBytes()?

For instance, if String is really large, 50MB, and there is no way to create another copy (getBytes() for another 50MB) of it due to resource constraints, it could potentially throw an out of memory error.

I just wanted to know if above lines of code is the efficient way to generate InputStream from String. For instance, is there a way which I can "stream" String into input stream without using additional memory? Like a Reader-like abstraction on top of String?

3 Answers
Related