title: Get size of String w/ encoding in bytes without converting to byte[]
body: <p>I have a situation where I need to know the size of a <code>String</code>/encoding pair, in bytes, but cannot use the <code>getBytes()</code> method because 1) the <code>String</code> is very large and duplicating the <code>String</code> in a <code>byte[]</code> array would use a large amount of memory, but more to the point 2) <code>getBytes()</code> allocates a <code>byte[]</code> array based on the length of the <code>String</code> * the maximum possible bytes per character. So if I have a <code>String</code> with 1.5B characters and UTF-16 encoding, <code>getBytes()</code> will try to allocate a 3GB array and fail, since arrays are limited to 2^32 - X bytes (X is Java version specific).</p>
  
  <p>So - is there some way to calculate the byte size of a <code>String</code>/encoding pair directly from the <code>String</code> object?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Here's a working implementation of jtahlborn's answer:</p>
  
  <pre><code>private class CountingOutputStream extends OutputStream {
      int total;
  
      @Override
      public void write(int i) {
          throw new RuntimeException("don't use");
      }
      @Override
      public void write(byte[] b) {
          total += b.length;
      }
  
      @Override public void write(byte[] b, int offset, int len) {
          total += len;
      }
  }
  </code></pre>