在我们想把文本按指定的宽度写到文件中时, 如作文本报表有几行几列,每列按一定的宽度输出内容,我们就可以用到下面操作了.
public class RptUtil {
public static char fillChar = 32;
private static void formatString(StringBuffer _cellBuf, String _value, int _size){
int len = _value.length();
int start = 0;
int end = 0;
String line = null;
for(int i=0;i<len/_size+1;i++){
start = i*_size;
end = start + _size;
if(end>len)
end=len;
line = _value.substring(start, end);
int cut = line.indexOf('/n');
if(cut>=0){
line = line.substring(0,cut);
if(cut==0){
_cellBuf.append(fillChar);
}else{
_cellBuf.append(line);
}
fillSubCell(_cellBuf, _size);
int ind = start+cut;
if(ind<len)
ind+=1;
_value=_value.substring(ind);
len = _value.length();
i=-1;
}else if(end==len){
_cellBuf.append(line);
fillSubCell(_cellBuf, _size);
}else if(_value.charAt(end)==32){
_cellBuf.append(line);
fillSubCell(_cellBuf, _size);
}else{
int l = line.lastIndexOf(32);
if(l<0){
_cellBuf.append(line);
}else{
line=line.substring(0,line.lastIndexOf(32)+1);
_cellBuf.append(line);
fillSubCell(_cellBuf, _size);
_value=_value.substring(start+l+1);
len = _value.length();
i=-1;
}
}
}
}
public static void fillSubCell(StringBuffer _strBuff, int _size){
int length = _strBuff.length();
while(length%_size!=0){
_strBuff.append(fillChar);
length++;
}
}
public static void main(String []agrs){
//String value = "Str = want to/n telltest you something tstst=important/n h1111111111 about hmmy life=,but I am afraid of the man dsf =sfsf sdfsf sfsf namd XXXX./n you can th abou the away....do you know i am very hugslslfy";
String value = "(continued) In the former part of this artical, i have mention that extensive reading i do not prefer to. ... The greates harm done to students of english in china isIntensive reading,L,L.Ris";
StringBuffer strBuf = new StringBuffer();
int size = 30;
formatString(strBuf, value, size);
int len = strBuf.length();//209
int row = len/size;//
for(int i=0;i<=row;i++){
int start = i*size;
int end = start+size;
if(end>len)
end=len;
System.out.println(strBuf.substring(start, end));
}
}
}