62,614
社区成员
发帖
与我相关
我的任务
分享
package houlei.java.util;
import java.io.UnsupportedEncodingException;
/**
* 这个类的功能类似于String对象的包装器类,由于String类不能被继承,
* 所以,也只是根据现有状况进行了一部分关于编码后的字节功能方面的扩展。<p>
* 在使用该类的对象时,尽量一个String对象,只创建一次对应的ByteString对象,因为构造器要进行转码操作。<br/>
* 该对象的其他方法可以多次调用也没关系,因为转码确实比较耗费CPU时间。
* @author HouLei
*/
public class ByteString {
public static final String DefaultCharsertName = "GBK";
private String value;//该参数用于本类功能的扩展,目前而言,可以除去。
private byte [] buff;
public ByteString(String value,String charsetName) throws UnsupportedEncodingException {
this.value = value;
buff = value.getBytes(charsetName);
}
public ByteString(String value) throws UnsupportedEncodingException {
this(value,DefaultCharsertName);
}
/**
* 获得字符串被转码以后所占的字节数。
* @return 所占字节数。
*/
public int size(){
return buff.length;
}
/**
* 将转码以后的字节数组进行切割,并返回切割后的字符数组。<br/>
* 该方法并不保证切割后的字节数组,仍然是完整的字符串。
* @param beginIndex 字节数组的开始位置。
* @param endIndex 字节数组的结束位置。
* @return 切割后的结果。
*/
public byte [] subBytes(int beginIndex,int endIndex){
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > buff.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
byte [] newBuff = new byte [endIndex - beginIndex];
System.arraycopy(buff, beginIndex, newBuff, 0, newBuff.length);
return newBuff;
}
/**
* 这个方法是示例代码,应该删除。
*/
public static void main(String args []) throws UnsupportedEncodingException{
String str="a您好b";
ByteString bs = new ByteString(str);//只要保持bs对象,就可以多次调用它的一些方法,这样效率就高了。
byte [] b1 = bs.subBytes(0, 1);
byte [] b2 = bs.subBytes(1, 3);
byte [] b3 = bs.subBytes(0, 3);
System.out.println(new String(b1,"GBK"));//可以得到从字节0开始的1个字节“a”
System.out.println(new String(b2,"GBK"));//可以得到从字节1开始的2个字节“您”而不是str.substring(0,3)的“您好”
System.out.println(new String(b3,"GBK"));//可以得到从字节1开始的2个字节“a您”而不是str.substring(0,3)的“a您好”
}
}