J2ME读取UTF-8编码文件方法

来源:互联网 发布:淘宝怎么看退货率 编辑:程序博客网 时间:2024/05/22 12:49
代码如下(简略版): private string name; private static font font; private final static byte enter_1 = (byte) 0x0d; //utf-8编码中换行字节1 private final static byte enter_2 = (byte) 0x0a; //utf-8编码中换行字节2 private static datainputstream dis; private static string[] strtxt; //类构造器,我的类名叫explorerscreen public explorerscreen(string name) { setfullscreenmode(true); //全屏 font = font.getdefaultfont(); this.name = name + ".txt"; //合并文件名 dis = new datainputstream(getclass().getresourceasstream(this.name)); strtxt = readtextutf8(dis); //读 addcommand(new command("返回", command.back, 1)); setcommandlistener(this); } public void paint(graphics g) { clearscreen(g); //清屏 drawbackgroup(g); //画背景 g.setcolor(redfont, greenfont, bluefont); //设置字体颜色 //打印文字 for (int i = 0, y = 0; i < strtxt.length; ++i) { g.drawstring(strtxt[i], 0, y, graphics.top | graphics.left); y += font.stringwidth("中"); } } public static string[] readtextutf8(datainputstream dis) { //实际的行数 int m = 0 ; //读取的总byte数 int total = 0; //存放字符串数组开始下标 int itmp = 0 ; //存放字符串数组的byte长度 int len = 0 ; //要跳3个字节,因为前3个字节是utf-8特有的标记 try { dis.skip(3); } catch (ioexception e1) { // todo auto-generated catch block e1.printstacktrace(); } byte[] b = new byte[1024]; //读缓冲 try { total = dis.read(b); //得到读了多少字节 system.out.println("total = " + total); } catch (ioexception e) { // todo auto-generated catch block system.out.println("total = dis.read(b);"); } for (int i = 0; i < total; ++i) { //判断有多少行 if (enter_1 == b[i] && enter_2 == b[i + 1]) { m++; } } string[] s = new string[m]; //建立结果数组,以行数为维数。 for (int i = 0, z = 0; i < total; i++) { //继续判断是否有空格,但这次是为了分行 if (enter_1 == b[i] && enter_2 == b[i + 1]) { len = i - itmp; //得到长度 try { s[z] = new string(b, itmp, len, "utf-8"); //转换并保存结果 } catch (unsupportedencodingexception e) { // todo auto-generated catch block system.out.println("(s[z] = new string"); } itmp = i + 2; //后跳2个字节,因为那是换行符 if (z < s.length) { z++; } } } return s; //返回结果 }
原创粉丝点击