RMS问题,请指教

kalends 2004-03-22 09:17:16
我在程序中向记录集存数据,想存进去中文字,,
但是,存进去的都是一些乱七八糟的东西,,
再用同样的方法读出来,也不是中文,,,
请各位高手指教,怎么样才能在记录集中,存取中文信息
...全文
56 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
witboy 2004-04-07
  • 打赏
  • 举报
回复
字符编码不要弄错,unicode和utf8不一样
kalends 2004-03-31
  • 打赏
  • 举报
回复
up
JavaAndJava 2004-03-23
  • 打赏
  • 举报
回复
String appt3 = "中文字符";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(appt3);
byte[] bytes3 = bos.toByteArray();
rs.addRecord(bytes3, 0, bytes3.length);

//从数据库中读出中文
byte b3[] = rs.getRecord(dbid);
DataInputStream dis=new DataInputStream(new ByteArrayInputStream(b3));
String chinastring = dis.readUTF();

writeUTF() 和 readUTF() 分别是DataOutputStream 和 DataInputStream对象的的方法,他们提供了一个由从Unicode到UTF-8的相互转化的途径。
仔细看看midp的说明文档,可以看到以下内容
writeUTF() :
First, two bytes are written to the output stream as if by the writeShort method giving the number o
f bytes to follow. This value is the number of bytes actually written out, not the length of the str
ing. Following the length, each character of the string is output, in sequence, using the UTF-8 enco
ding for the character.If no exception is thrown, the counter written is incremented by the total nu
mber of bytes written to the output stream. This will be at least two plus the length of str, and at
most two plus thrice the length of str.

当然我们也可以自己来手工的编写代码,把中文字符串转化成byte[]再放入RMS,取出时转成String即可。
这里借用bingo_guan的方法(bingo_guan,请不要介意呀 :)),当然了这段代码也非常的设计模式化 hehe,这个类也可用于文本文件操作。

/**
* <p>Title: </p>
* <p>Description: unicode字串转换工具</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: CC Studio</p>
* @author Bingo
* @version 1.0
*/

public class UnicodeString
{

public UnicodeString()
{
}

public static String byteArrayToString(byte abyte0[], int i)
{
StringBuffer stringbuffer = new StringBuffer("");
for(int j = 0; j < i; )
{
int k = abyte0[j++]; //注意在这个地方进行了码制的转换
if(k < 0)
k += 256;
int l = abyte0[j++];
if(l < 0)
l += 256;
char c = (char)(k + (l << 8));//把高位和低位数组装起来
stringbuffer.append(c);
}

return stringbuffer.toString();
}

public static String byteArrayToString(byte abyte0[])
{
return byteArrayToString(abyte0, abyte0.length);
}

public static byte[] stringToByteArray(String s)
{
int i = s.length();
byte abyte0[] = new byte[i << 1];
int j = 0;
for(int k = 0; k < i; k++)
{
char c = s.charAt(k);
abyte0[j++] = (byte)(c & 0xff); //每一个位按位转化
abyte0[j++] = (byte)(c >> 8);
}

return abyte0;
}
}
kalends 2004-03-23
  • 打赏
  • 举报
回复
up
kalends 2004-03-23
  • 打赏
  • 举报
回复
up
kalends 2004-03-22
  • 打赏
  • 举报
回复
在模拟器上可以正常显示
但是到了实机上,就显示不出来了,,,
JavaAndJava 2004-03-22
  • 打赏
  • 举报
回复
看看王森的书啊!
mingjava 2004-03-22
  • 打赏
  • 举报
回复
模拟器也可以输入中文吗? 我没有输到里面去 :)



auglyguy 2004-03-22
  • 打赏
  • 举报
回复
搜索一下论坛吧,以前有很多这样的帖子了
usingpete 2004-03-22
  • 打赏
  • 举报
回复
在模拟器上面有问题可能上真机就没有了

13,100

社区成员

发帖
与我相关
我的任务
社区描述
Java J2ME
社区管理员
  • J2ME社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧