在J2ME程序設(shè)計過程中,在存儲記錄集、網(wǎng)絡(luò)傳輸數(shù)據(jù)、以及讀取資源文件中的數(shù)據(jù)時,都可能存在中文問題。
中文問題的本質(zhì)是保存、傳輸中文時使用的字符編碼和讀取、獲得中文時的字符編碼不同。在J2ME中所有的手機都支持UTF-8格式的字符集。
在使用數(shù)據(jù)的時候,一般出現(xiàn)中文問題是在將字符串和字節(jié)數(shù)組轉(zhuǎn)換的時候產(chǎn)生,下面是編碼中文產(chǎn)生亂碼的轉(zhuǎn)換方法:
import java.io.*;
public class Test
{
/**
* 將字節(jié)數(shù)組轉(zhuǎn)換為字符串
* @param bytes 需要轉(zhuǎn)換的字節(jié)數(shù)組
* @return 轉(zhuǎn)換后的字符串
*/
public static String byte2String(byte[] bytes)
{
try
{
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bais);
String s = dis.readUTF();
//關(guān)閉流
dis.close();
bais.close();
return s;
}
catch(Exception e)
{
return null;
}
}
/**
* 將字符串轉(zhuǎn)換為字節(jié)數(shù)組
* @param s 需要轉(zhuǎn)換的字符串
* @return 轉(zhuǎn)換后生成的字節(jié)數(shù)組
*/
public static byte[] string2Byte(String s)
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream bos = new DataOutputStream(baos);
bos.writeUTF(s);
byte[] bytes = baos.toByteArray();
//關(guān)閉流
bos.close();
baos.close();
return bytes;
}
catch(Exception e)
{
return null;
}
}
}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。