Java/Source2009. 4. 3. 13:10

byte 배열 형식의 데이터를 바이트 크기로 자르는 경우 숫자나 알파벳만 들어 있는 경우는 문제가 되지 않으나 2바이트를 쓰는 언어(한국어 등)의 경우 중간에서 잘리게 되면 ?로 표시가 되게 된다.

따라서 아래와 같은 코드로 유니코드의 중간에서 잘리는 경우를 막아주어야 한다.

========================================================================

protected String subBytes(byte[] str, int len) {
    if(str.length <= len) {
        return new String(str);
    } else {
        int cntMinusBytes = 0;

        for(int i=0; i<len; i++)
            cntMinusBytes += (str[i] < 0) ? 1 : 0;

        if (cntMinusBytes % 2 != 0)
            len--;

        return new String(str, 0, len);
    }
}

protected String subBytes(String str, int len) {
    return subBytes(str.getBytes(), len);
}
Posted by Huikyun