title: InputStream via ReadableByteChannel does not read to end
body: <p>I have an existing problem where I am using InputStreams and I want to increase the performance of reading from this channel. Therefore i read with a <code>ReadableByteChannel</code>.</p>
  
  <p>As a result the reading is much faster with this code:</p>
  
  <pre><code>public static String readAll(InputStream is, String charset, int size) throws IOException{
  
      try(ByteArrayOutputStream bos = new ByteArrayOutputStream()){
          java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(size);
  
          try(ReadableByteChannel channel = Channels.newChannel(is)){
  
              int bytesRead = 0;
  
              do{
                  bytesRead = channel.read(buffer);
                  bos.write(buffer.array(), 0, bytesRead);
                  buffer.clear();
              }
              while(bytesRead &gt;= size);
          }
          catch(Exception ex){
              ex.printStackTrace();
          }
          String ans = bos.toString(charset);
          return ans;
      }
  }
  </code></pre>
  
  <p>The Problem is: <strong>It does not read to the end every time!</strong> If I try to read a File it works pretty good. If I read from a network Socket (to request a WebPage manually for example) it sometimes stops somewhere in between.</p>
  
  <p>What can I do to read to the end?</p>
  
  <p>I don't want to use something like this:</p>
  
  <pre><code>StringBuilder result = new StringBuilder();
  while(true){
      int ans = is.read();
      if(ans == -1) break;
      result.append((char)ans);
  }
  return result.toString();
  </code></pre>
  
  <p>because this implementation is slow.</p>
  
  <p>I hope you can help me with my problem. maybe i have some mistake in my code.</p>