J2ME中讀取Unicode和UTF-8編碼文件的方法

一、讀取Unicode 文件

    /**

     * 讀取Unicode 編碼文本文件

     * @param resource String - 文件名

     * @return String - Unicode 文本

     */

    public static String read_Uni(String resource) {

        byte word_uni[] = new byte[1024];

        String strReturn = null;

        InputStream is;

        try {

            is = instance.getClass().getResourceAsStream(resource);

            is.skip(2);            // 跳過兩個字節的文件頭

            is.read(word_uni);

            is.close();

            StringBuffer stringbuffer = new StringBuffer("");

            for (int j = 0; j < word_uni.length; ) {

                int l = word_uni[j++];

                int h = word_uni[j++];

                char c = (char) ((l & 0xff) | ((h << 8) & 0xff00));

                stringbuffer.append(c);

            }

            strReturn = stringbuffer.toString();

        } catch (IOException ex) {

            System.out.println(ex);

        } finally {

            is = null;

        }

        return strReturn;

}

二、讀取UTF-8 文件

    /**

     * 讀取UTF-8 編碼文本文件

     * @param resource String - 文件名

     * @return String - UTF-8 文本

     */

    public static String read_UTF(String resource) {

        byte word_utf[] = new byte[1024];

        String strReturn = null;

        InputStream is;

        try {

            is = instance.getClass().getResourceAsStream(resource);

            is.read(word_utf);

            is.close();

            strReturn = new String(word_utf, "UTF-8");

        } catch (IOException ex) {

            System.out.println(ex);

        }

        return strReturn;

   }

 

備註:

InputStream in=this.getClass().getResourceAsStream("/help.txt") ;//將位於res目錄下的help.txt中數字讀出。

……

in.mark(0);

……

in.reset();

發佈了103 篇原創文章 · 獲贊 17 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章