/** 바이트로 문자열을 자를 경우 홀수로 자를 경우 마지막 바이트는 깨진 문자가
들어가는 경우가 발생 할 수도 있다. 이럴 경우 정상인 바이트에 깨진 바이트를
공백으로 처리 하여 합치는 방법이다.
박세청 cozyhill@hanmail.net
**/
class CutBytes
{
//해당제한 바이트 만큼 자른 다음 모자라는 바이트는 공백으로 채운다.
public static boolean setFilter(int length, byte[] data) {
if(length<data.length){
String value = new String(data);
int len = 0;
for(int i =0;i<value.length();i++){
//1바이트, 2바이트, 3바이트 문자만큼 길이 합산
len += value.substring(i, i+1).getBytes().length;
if(length<len){
for(int j=value.substring(0,i).getBytes().length; j< data.length;j++){
data[j] = 32; //공백으로 집어 넣음
}
break;
}
}
}
return false;
}
public static void main(String[] args) throws Exception
{
String str ="가나";
byte[] b = str.getBytes();
int length = 3; //3bytes까지 허용
System.out.println("문자열: "+ str);
System.out.println("바이트수: "+ b.length);
//한글은 2byte문자로 홀수로 자르경우 문제가 발생한다.
System.out.println("홀수로 자른 문자열: "+ new String(b,0,length));
//필터적용후 문자를 자르고 모자른 바이트는 공백처리
setFilter(length, b);
//공백처리됨
System.out.println("공백처리된 문자열|"+(new String(b,0,length))+"|");
System.out.println("바이트수: "+ (new String(b,0,length)).getBytes().length);
}
}