這三種方法都能讀取中文和英文字符.用來存放的數組長度視文本長度而定....
另外還有一些只能讀取英文字符的方法就不列舉出來了.
一、讀取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 |
作者: syngle 出處: J2ME開發網