Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

memory management - 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.

question from:https://stackoverflow.com/questions/65541132/how-to-convert-reader-to-inputstream-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...