Search code examples
javamemory-managementinputstreamreader

How to convert Reader to InputStream in java


I need to convert a Reader object into InputStream. My solution right now is below. But my concern is since this will handle big chunks of data, it will increase the memory usage drastically.

private static InputStream getInputStream(final Reader reader) {
   char[] buffer = new char[10240];
   StringBuilder builder = new StringBuilder();
   int charCount;
   try {
      while ((charCount = reader.read(buffer, 0, buffer.length)) != -1) {
         builder.append(buffer, 0, charCount);
      }
      reader.close();
   } catch (final IOException e) {
      e.printStackTrace();
   }
   return new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8));
}

Since I use StringBuilder this will keep the full content of the reader object in memory. I want to avoid this. Is there a way I can pipe Reader object? Any help regarding this highly appreciated.


Solution

  • Using the Apache Commons IO library, you can do this conversion in one line:

    //import org.apache.commons.io.input.ReaderInputStream;
    
        
        InputStream inputStream = new ReaderInputStream(reader, StandardCharsets.UTF_8);
    

    You can read the documentaton for this Class at https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReaderInputStream.html

    It might be worth trying this to see if it solves the memory issue too.