简体   繁体   中英

Read special characters in java

I have a question, I'm trying to read from a file, a set of key and value pairs ( Like a Dictionary). For this I'm using the following code:

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

And the readLine function.

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

Everything is fine, however I want it to be able to parse special characters. For example: ó that would be codified into \ó, however in this case it's not replacing it with the correct character... What would be the way to do it?

EDIT: Forgot to say that since I'm using JavaME the Properties class or anything similar does not exist, that's why it may seem that I'm reinventing the wheel...

If it's encoded with UTF-16, can you not just InputStreamReader isr = new InputStreamReader(is, "UTF16") ?

This would recognize your special characters right from the get-go and you wouldn't need to do any replacements.

You need to ensure that you character encoding is set in your InputStreamReader to be that of the file. If it doesn't match some characters can be incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM