`
juansusan
  • 浏览: 70650 次
  • 性别: Icon_minigender_2
  • 来自: 大连
社区版块
存档分类
最新评论

J2ME读取本地Unicode编码的文本文件

阅读更多
import java.io.*;

import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class LoadText extends MIDlet implements CommandListener
{
private Display display;
private Form mainForm;
private TextField textField;
public void startApp()
{
   this.display = Display.getDisplay(this);
   this.mainForm = new Form("读取Unicode编码的文本文件");
   this.textField = new TextField("靠自己","hello",10240,TextField.ANY);
   this.mainForm.addCommand(new Command("离开", Command.EXIT, 0));
   String str = loadText("/cunwang(Unicode).txt");
   this.textField.setString(str);
   this.mainForm.append(this.textField);
   this.mainForm.setCommandListener(this);
   this.display.setCurrent(mainForm);

}


public void pauseApp()
{


public void destroyApp(boolean unconditional)
{
}



public void commandAction(Command c, Displayable s)
{
   this.notifyDestroyed();
}


//读取Unicode编码的文本文件 (没问题)
private String loadText(String resource)
{
byte[] word_uni = new byte[1024];
String strReturn = "";
InputStream is;//此抽象类是表示字节输入流的所有类的超类
try
{
   is = this.getClass().getResourceAsStream(resource);
   is.read(word_uni);//从输入流中读取一定数量的字节并将其存储在缓冲区字节数组 b 中。
   is.close();
   StringBuffer stringbuffer = new StringBuffer("");
   for(int j = 0; j < word_uni.length;)
   {
    int k = word_uni[j++];//这个地方进行了码制的转换
    if(k < 0)
    k += 256;
    int l = word_uni[j++];
    if(l < 0)
    l += 256;
    char c = (char)(k + (l <<8));//把高位和低位数组装起来
    stringbuffer.append(c);
   }
   strReturn = stringbuffer.toString();
}
catch(IOException e)
{
   e.printStackTrace();
}
finally
{
   is = null;
}
return strReturn;
}


}



/*

cunwang(Unicode).txt文件内容如下:
----------------------------------
春望
杜甫
国破山河在,城春草木深。
感时花溅泪,恨别鸟惊心。
烽火连三月,家书抵万金。
白头搔更短,浑欲不胜簪。
----------------------------------
注意在记事本中保存时类型要选择Unicode
把这个文件保存到项的res目录下,如:
C:\WTK25\apps\LoadTxt_pro\res

*/
分享到:
评论
1 楼 wishwingliao 2009-01-16  
转我的是吧:)

http://hi.baidu.com/wishwingliao/blog/item/0a129f5003ff59648535240a.html

相关推荐

Global site tag (gtag.js) - Google Analytics