Skip to content

Instantly share code, notes, and snippets.

@donaldh
Last active December 21, 2015 17:59
Show Gist options
  • Save donaldh/6344106 to your computer and use it in GitHub Desktop.
Save donaldh/6344106 to your computer and use it in GitHub Desktop.
Unhelpful behaviour of Java ChsrsetEncoder
package test;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class Encode {
/**
* @param args
*/
public static void main(String[] args) {
String s = "0123456789\nABCDEFG\n風, 薔薇, バズ\n";
System.out.println("String length: " + s.length());
try {
CharsetEncoder enc = Charset.forName("UTF-8").newEncoder();
CharBuffer charbuf = CharBuffer.wrap(s);
System.out.println("Charbuf pos: " + charbuf.position() + " limit: " + charbuf.limit());
ByteBuffer bytebuf = enc.encode(charbuf);
System.out.println("Bytebuf pos: " + bytebuf.position() + " limit: " + bytebuf.limit());
} catch (CharacterCodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
String length: 29
Charbuf pos: 0 limit: 29
Bytebuf pos: 0 limit: 39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment