CharBuffer vs. char[]

Chris Conway picture Chris Conway · Nov 16, 2008 · Viewed 43.5k times · Source

Is there any reason to prefer a CharBuffer to a char[] in the following:

CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
  out.append( buf.flip() );
  buf.clear();
}

vs.

char[] buf = new char[DEFAULT_BUFFER_SIZE];
int n;
while( (n = in.read(buf)) >= 0 ) {
  out.write( buf, 0, n );
}

(where in is a Reader and out in a Writer)?

Answer

erickson picture erickson · Nov 16, 2008

No, there's really no reason to prefer a CharBuffer in this case.

In general, though, CharBuffer (and ByteBuffer) can really simplify APIs and encourage correct processing. If you were designing a public API, it's definitely worth considering a buffer-oriented API.