簡體   English   中英

在java中讀取特殊字符

[英]Read special characters in java

我有一個問題,我正在嘗試從一個文件,一組鍵和值對(像一個字典)中讀取。 為此,我使用以下代碼:

 InputStream is = this.getClass().getResourceAsStream(PROPERTIES_BUNDLE);
     properties=new Hashtable();

     InputStreamReader isr=new InputStreamReader(is);
     LineReader lineReader=new LineReader(isr);
     try {
        while (lineReader.hasLine()) {
            String line=lineReader.readLine();
            if(line.length()>1 && line.substring(0,1).equals("#")) continue;
            if(line.indexOf("=")!=-1){
                String key=line.substring(0,line.indexOf("="));
                String value=line.substring(line.indexOf("=")+1,line.length());
                properties.put(key, value);
            }               
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

和readLine函數。

  public String readLine() throws IOException{
    int tmp;
    StringBuffer out=new StringBuffer();
    //Read in data
    while(true){
        //Check the bucket first. If empty read from the input stream
        if(bucket!=-1){
            tmp=bucket;
            bucket=-1;
        }else{
            tmp=in.read();
            if(tmp==-1)break;
        }
        //If new line, then discard it. If we get a \r, we need to look ahead so can use bucket
        if(tmp=='\r'){
            int nextChar=in.read();
            if(tmp!='\n')bucket=nextChar;//Ignores \r\n, but not \r\r
            break;
        }else if(tmp=='\n'){
            break;
        }else{
            //Otherwise just append the character
            out.append((char) tmp);
        }
    }
    return out.toString();
}

一切都很好,但我希望它能夠解析特殊字符。 例如:ó將被編入“u0​​0F3”,但在這種情況下,它不會用正確的字符替換它......這樣做的方法是什么?

編輯:忘了說,因為我使用JavaME屬性類或類似的東西不存在,這就是為什么它似乎我正在重新發明輪子...

如果它是用UTF-16編碼的,那么你不僅僅是InputStreamReader isr = new InputStreamReader(is, "UTF16")嗎?

這將從一開始就識別您的特殊字符,您不需要進行任何替換。

您需要確保在InputStreamReader中將字符編碼設置為文件的編碼。 如果不匹配某些字符可能不正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM