SFTP 형식의 파일 교환시에 길이를 고정한 상태로 빈 문자열을 0으로 채워야하는 업무가 있었다.
어떻게 해결해야 할지 고민 하다가 빈값을 채우는 알고리즘을 만들어 둔 소스를 찾을 수 있었다.
자세한 설명은 소스상에 주석을 달아 설명해두었으니 참고하길 바랍니다.
privatefinalstaticint LEFT = 0;
privatefinalstaticint RIGHT = 1;
/**
* String 형의 자료를 입력받아 길이만큼 문자를 채워서 리턴하는 method
*
* inputData : 원데이타
* align : 0 - left, 1 - right (어느쪽에 원 데이타를 둘건지...)
* fillSize : 늘리고자하는 길이
* fillChar : 채울 문자
*
* 예) : fmt("string", 1, 10, '0') => "0000string"
*/publicstatic StringformatData(String data,int align,int fillSize,char fillChar) {
if (data ==null) {
data = "";
}
byte[] bytes = data.getBytes();
int len = bytes.length;
if (len < fillSize) {// 모자라는 길이만큼 채울 문자열을 만든다.if (align == LEFT) {
StringBuffer strbuf =newStringBuffer(data);
for (int i = len; i < fillSize; i++) {
strbuf.append(fillChar);
}
return strbuf.toString();
}
else {
StringBuffer strbuf =newStringBuffer();
for (int i = len; i < fillSize; i++) {
strbuf.append(fillChar);
}
strbuf.append(data);
return strbuf.toString();
}
}
else {
// 원하는 길이보다 크면 잘라 보낸다.// 한글이 잘리는 경우 잘리는 글자는 제외String tmp = "";
if(align == LEFT){
int idx = getUniLength(bytes, fillSize, LEFT);
tmp =newString(bytes, 0, idx);
if(idx < fillSize){
StringBuffer strbuf =newStringBuffer(tmp);
for(int i=idx; i<fillSize; i++){
strbuf.append(fillChar);
}
return strbuf.toString();
}else{
if(tmp.equals("")) tmp =newString(bytes, 0, fillSize-1) + " ";
return tmp;
}
}
else {
int idx = getUniLength(bytes, fillSize, RIGHT);
tmp =newString(bytes, idx, bytes.length-idx);
if(bytes.length-idx < fillSize){
StringBuffer strbuf =newStringBuffer();
for(int i=bytes.length-idx; i<fillSize; i++){
strbuf.append(fillChar);
}
strbuf.append(tmp);
return strbuf.toString();
}else{
if(tmp.equals("")) tmp =newString(bytes, len - fillSize + 1, fillSize) + " ";
return tmp;
}
}
}
}
privatestaticintgetUniLength(byte[] bytes,int size,int align) {
int idx = 0;
if(align == LEFT) {
for(idx = 0; idx < bytes.length && idx < size ; idx++) {
if(bytes[idx] > 127 || bytes[idx] < 0) {
idx++;
}
}
if(idx> size) idx = idx - 2;
}else {
for(idx = 0; idx < bytes.length - size ; idx++) {
if(bytes[idx] > 127 || bytes[idx] < 0) {
idx++;
}
}
}
return idx;
}