在java中读取特殊字符

时间:2012-05-28 17:05:47

标签: java parsing character-encoding character

我有一个问题,我正在尝试从一个文件,一组键和值对(像一个字典)中读取。为此,我使用以下代码:

 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();
}

一切都很好,但我希望它能够解析特殊字符。例如:ó将被编入\ u00F3,但是在这种情况下,它不会用正确的字符替换它......这样做的方法是什么?

编辑:忘了说因为我使用JavaME,所以不存在属性类或任何类似的东西,这就是为什么看起来我正在重新发明轮子......

2 个答案:

答案 0 :(得分:2)

如果它是用UTF-16编码的,你不能只是 InputStreamReader isr = new InputStreamReader(is, "UTF16")

这将从一开始就识别你的特殊字符,你不需要做任何替换。

答案 1 :(得分:1)

您需要确保在InputStreamReader中将字符编码设置为文件的编码。如果不匹配某些字符可能不正确。