this is a extra element for clear the floated element
在J2ME中读取各种格式的文本文件
  • 12/31
  • 2008
核心技术 | Java 2939 次查看
  在J2ME开发过程中,我们经常会把一个文字信息保存在txt格式的文本文件中做为资源。这样便于修改和管理。那么读取它们对于一些刚接触j2me的朋友会有些困难。前几天研究了下,看了一些兄弟的文章和代码,总结出3种方法分别读取Unicode,UTF-8,Unicode big endian格式的文件...本文没考虑读取的效率问题。

  这三种方法都能读取中文和英文字符.用来存放的数组长度视文本长度而定....

  另外还有一些只能读取英文字符的方法就不列举出来了.

  一、读取Unicode格式

  private String read_Uni(String resource)

  {

  byte word_uni[]=new byte[1024];

  String strReturn="";

  InputStream is;

  try

  {

  is=getClass().getResourceAsStream(resource);

  is.read(word_uni);

  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;

  }

  读取Unicode big endian格式时,采用readChar()方法读取,所以存放时使用char数组存放。

  注意:在文本的末尾加上'$'表示文本的结束。

  另外代码第10行dis.skip(2)是略过文件头2个字符,如果用microsoft notepad保存的一定存在这两个头字符。

  当然,可以使用UltraEdit可以先删掉这两个头字符,然后使用新建文件,复制粘贴,保存为其它格式.这样两个头字符就没了..

  private String read_Uni_b_e(String resource)

  {

  char word_uni_b_e[]=new char[1024];

  String strReturn="";

  DataInputStream dis;

  try

  {

  dis=new DataInputStream(getClass().getResourceAsStream(resource));

  int counter=0;

  dis.skip(2);

  char temp;

  while(true)

  {

  temp=dis.readChar();

  if(temp=='$')

  break;

  word_uni_b_e[counter++]=temp;

  }

  dis.close();

  strReturn=String.valueOf(word_uni_b_e,0,counter);

  }

  catch(Exception e)

  {

  System.out.println("read_Uni_b_e error!"+e.getMessage());

  }

  finally

  {

  dis=null;

  }

  return strReturn;

  }

  以上3种方法测试平台:

  Operation System: Microsoft Windows XP Professional Service Pack 1

  Emulator: Sun Wireless ToolKit 2.2 beta DefaultColorPhone
您可能感兴趣的:

更多相关内容