日期:2014-05-20  浏览次数:21036 次

InputStreamReader的编码问题,怎么整都出不来
以下是小程序:public   class   InputStreamReaderDemo   {
public   static   void   main(String[]   args)   throws   IOException   {
try   {
int   b;
InputStreamReader   isr   =   new   InputStreamReader(
new   FileInputStream(
"D:\\default.txt "),
"GBK ");
StringBuilder   sb=new   StringBuilder();
System.out.println( "The   content   of   text   is: ");
while   ((b   =   isr.read())   !=   -1)//   顺序读取文件text里的内容并赋值给整型变量b,直到文件结束为止。
{
sb.append((char)   b);
}
isr.close();
System.out.println(sb.toString());
}   catch   (FileNotFoundException   e)   {
System.out.println(e);
}   catch   (IOException   e)   {
System.out.println(e);
}   catch   (Exception   e)   {
System.out.println(e);
}
}
}

D:\\default.txt中的内容为“这是中文测试”,不知道为什么只有用UTF-8去读才没问题。

后来随便写了个,也还是乱码:
String   encoding   =   "GBK ";
InputStreamReader   reader   =   new   InputStreamReader(new   FileInputStream(
"d:\\default.txt "),   encoding);
char   c[]   =   new   char[10];
int   length   =   reader.read(c);
System.out.println(new   String(c));



------解决方案--------------------
似乎跟底层的编码方式有关
我的系统是Windows XP中文版,用GBK编码能正确的读出来,但用UTF-8编码读则是乱码。

建议你把编码的那个字符串换成Charset.defaultCharset().displayName()试试,即
InputStreamReader isr = new InputStreamReader(new FileInputStream( "D:\\default.txt "), Charset.defaultCharset().displayName());
------解决方案--------------------
和default.txt文件的编码方式有关。

------解决方案--------------------
既然是汉字的话,为什么不用BufferedReader呢?
BufferedReader br = new BufferedReader(new FileReader( "D:\\default.txt "));
while ((b = br.readLine()) != null){
....
}