彻底解决J2ME中的中文问题 - 中国WEB开发者网络 (http://www.webasp.net) -- 技术教程 (http://www.webasp.net/article/) --- 彻底解决J2ME中的中文问题 (http://www.webasp.net/article/26/25988.htm) |
| -- 作者:未知 -- 发布日期: 2005-08-18 |
在J2ME程序设计过程中,在存储记录集、网络传输数据、以及读取资源文件中的数据时,都可能存在中文问题。 中文问题的本质是保存、传输中文时使用的字符编码和读取、获得中文时的字符编码不同。在J2ME中所有的手机都支持UTF-8格式的字符集。
在使用数据的时候,一般出现中文问题是在将字符串和字节数组转换的时候产生,下面是编码中文产生乱码的转换方法:
import java.io.*;
public class Test{
/**
* 将字节数组转换为字符串
* @param bytes 需要转换的字节数组
* @return 转换后的字符串
*/
public static String byte2String(byte[] bytes){
try{
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bais);
String s = dis.readUTF();
//关闭流
dis.close();
bais.close();
return s;
}catch(Exception e){
return null;
}
}
/**
* 将字符串转换为字节数组
* @param s 需要转换的字符串
* @return 转换后生成的字节数组
*/
public static byte[] string2Byte(String s){
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream bos = new DataOutputStream(baos);
bos.writeUTF(s);
byte[] bytes = baos.toByteArray();
//关闭流
bos.close();
baos.close();
return bytes;
}catch(Exception e){
return null;
}
}
}在J2ME程序设计过程中,在存储记录集、网络传输数据、以及读取资源文件中的数据时,都可能存在中文问题。
中文问题的本质是保存、传输中文时使用的字符编码和读取、获得中文时的字符编码不同。在J2ME中所有的手机都支持UTF-8格式的字符集。 在使用数据的时候,一般出现中文问题是在将字符串和字节数组转换的时候产生,下面是编码中文产生乱码的转换方法:
import java.io.*; public class Test{
/** * 将字节数组转换为字符串 * @param bytes 需要转换的字节数组 * @return 转换后的字符串 */ public static String byte2String(byte[] bytes){ try{ ByteArrayInputStream bais = new ByteArrayInputStream(bytes); DataInputStream dis = new DataInputStream(bais);
String s = dis.readUTF();
//关闭流 dis.close(); bais.close();
return s;
}catch(Exception e){ return null; } }
/** * 将字符串转换为字节数组 * @param s 需要转换的字符串 * @return 转换后生成的字节数组 */ public static byte[] string2Byte(String s){ try{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream bos = new DataOutputStream(baos);
bos.writeUTF(s);
byte[] bytes = baos.toByteArray();
//关闭流 bos.close(); baos.close();
return bytes; }catch(Exception e){ return null; } } } |
| webasp.net |