在J2ME開發過程中,我們經常會把一個文字信息保留在txt格局的文本文件中做為資源.這樣便於修正和治理.那麼讀取它們對於一些剛接觸J2ME的朋友會有些艱苦.前幾天研究了下,看了一些兄弟的文章和代碼,總結出3種方法分辨讀取Unicode,UTF-8,Unicode bigendian格局的文件...本文沒考慮讀取的效率標題.
這三種方法都能讀取中文和英文字符.用來存放的數組長度視文本長度而定....
另外還有一些只能讀取英文字符的方法就不列舉出來了.
一,讀取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;}以上3種方法測試平台:
Operation System: Microsoft Windows XP Professional Service Pack 1
Emulator: Sun Wireless ToolKit 2.2 beta DefaultColorPhone