Skip to content

Instantly share code, notes, and snippets.

@seraphy
Created December 29, 2012 10:36
Show Gist options
  • Save seraphy/4405999 to your computer and use it in GitHub Desktop.
Save seraphy/4405999 to your computer and use it in GitHub Desktop.
文字列を、指定されたキャラクターセットでバイト化する場合、 指定サイズのバイト配列に格納できる最大の文字数に文字列を分割する。
public static void main(String[] args) throws Exception {
String encName = "UTF-8";
String message = "1あいうえおかきくけ23こさ4";
int bufsiz = 512;
Charset charset = Charset.forName(encName);
CharsetEncoder enc = charset.newEncoder();
CharBuffer chrbuf = CharBuffer.wrap(message);
ByteBuffer buf = ByteBuffer.allocate(bufsiz);
CoderResult ret;
do {
ret = enc.encode(chrbuf, buf, false);
if (ret.isOverflow() && buf.position() == 0) {
// バッファに1バイトも書き込まれずにオーバーフローしたら
// 何度繰り返しても変換は不可能である.
throw new RuntimeException("buffer is too small.");
}
// バッファに入りきる文字分だけ書き出されたら、
// 書き込まれたバッファ分の文字列を受け取る.
buf.flip();
CharBuffer splitChars = charset.decode(buf);
System.out.println("str=" + splitChars.toString());
buf.clear();
} while (ret.isOverflow());
System.out.println("done");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment