我有一个问题,我试图从文件中读取一组键和值对(如字典)。为此,我使用以下代码:阅读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();
}
一切都很好,但我希望它能够解析特殊字符。例如: - 这将被编入\ u00F3,但在这种情况下,它不会用正确的字符替换它......将有什么办法做到这一点?
编辑:忘了说,因为我使用的JavaME Properties类或任何类似不存在,这就是为什么它可能看起来我重新发明轮子...
尝试以下操作:isr = new InputStreamReader(is,“UTF8”);然而它没有奏效...不得不提及我正在使用JavaME – Pablo
它编码了什么? UTF8或UTF16?由于UTF8与ASCII类似,并且不正确地读取它会丢失字符。 –
只是将文档更改为UTF8,但不是结果... – Pablo