可能对其他人和以后的程序有点启发作用,本想为自己的手机支持GBK做点努力,可没想到J2ME在调试上,内存上困难重重。下面的这些代码,可能对一些人有点用。
先是制作一个小映射字库:
public class GBK_Mapping {
public void save() throws IOException{
File file = new File(”utf.gbk”);
FileOutputStream fos = new FileOutputStream(file);
for (int i=0×81;i<0xfe;i++){
for (int j=0×40;j<0xff;j++){
GBK GBK = new GBK((byte)i,(byte)j);
String utf16 = new String(GBK.word(),”GBK”);
byte[] utf8 = utf16.getBytes(”UTF-8″);
byte[] gbk = GBK.word();
byte[] utfINT = new byte[3];
// byte[] gbkINT = new byte[4];
System.arraycopy(utf8, 0, utfINT,3-utf8.length, utf8.length);
// System.arraycopy(gbk, 0, gbkINT, 2, gbk.length);
// int utfVal = Primitive.bytesToInt(utfINT);
// int gbkVal = Primitive.bytesToInt(gbkINT);
// if (utf8.length==2)
// System.out.print(utf16);
fos.write(utfINT);
fos.write(gbk);
}}
fos.flush();
fos.close();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
GBK_Mapping gbkm = new GBK_Mapping();
gbkm.save();
}
}
然后是读取字库,可惜J2ME实在做不到这点,J2SE.DESKTOP则一切正常:
public class GBK_Loading {
// private Hashtable utfgbk;
public GBK_Loading(){
// utfgbk = new Hashtable();
}
public int get(int utfChk){
byte[] utf8 = new byte[3];
byte[] gbk = new byte[2];
byte[] utfINT = new byte[4];
byte[] gbkINT = new byte[4];
InputStream is = this.getClass().getResourceAsStream(”utf.gbk”);
DataInputStream dis = new DataInputStream(is);
try {
while (true){
int len_utf8;
len_utf8 = dis.read(utf8);
if (len_utf8<0)
break;
dis.read(gbk);
System.arraycopy(utf8, 0, utfINT, 1, 3);
System.arraycopy(gbk, 0, gbkINT, 0, 2);
int utfVal = Primitive.bytesToInt(utfINT);
int gbkVal = Primitive.bytesToInt(gbkINT);
if (utfChk==utfVal){
is.close();
return gbkVal;
}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public byte[] gbk(byte[] utf8){
byte[] utfINT = new byte[4];
System.arraycopy(utf8, 0, utfINT, 4-utf8.length, utf8.length);
int utfVal = Primitive.bytesToInt(utfINT);
byte[] gbk= utf8;
if (utf8.length>=2){
byte[] gbkINT = Primitive.intTobytes(get(utfVal));
gbk = new byte[2];
System.arraycopy(gbkINT, 0, gbk, 0, gbk.length);
}
return gbk;
}
public byte[] getGBK_Bytes(String str) throws UnsupportedEncodingException{
// System.out.println(utfgbk.size());
int len = str.length();
byte[] gbks = new byte[len*2];
for (int i=0;i<len;i++){
byte[] utf8 =(”"+str.charAt(i)).getBytes(”UTF-8″);
System.arraycopy(gbk(utf8), 0, gbks, i*2, 2);
}
return gbks;
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
GBK_Loading gbkm = new GBK_Loading();
System.out.println(new String(gbkm.getGBK_Bytes(”倒珍仍遥霜丂”),”GBK”));
byte[] gbks = gbkm.getGBK_Bytes(”丂”);
String gbkshex = Hex.as(gbks);
System.out.println(gbkshex);
System.out.println(new String(gbks,”GBK”));
}
}



