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;
    }
二, UTF-8格式
    public String read_UTF(String name)
    {
        String strReturn = “”;
        InputStream in = null;
        byte[] word_utf= new byte[1024];
        try
        {
          in = getClass().getResourceAsStream(name);
          in.read(word_utf);
          in.close();
          strReturn=new String(word_utf,”UTF-8”);
        }
        catch(Exception e)
        {
          System.out.println(“readUTF Error:”+e.toString());
        }
        finally
        {
          in = null;
        }
        return strReturn;
    }
三, Unicode big endian格式
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;
    }