以下是小程序: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));
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());
打印了Charset.defaultCharset().displayName())结果为GBK
BufferedReader br = new BufferedReader(new FileReader("D:\\default.txt"));
while ((b = br.readLine()) != null){
....
}
我在使用velocity时编写模板文件*.vm时文件是直接从velocity给的example里拷贝出来的。
后来自个新建了个文件再把内容拷贝进去后使用new InputStreamReader(new FileInputStream("D:\\default.txt"), "GBK");乱码问题便没有出现。
现在 写程序为了国际化、兼容各种操作系统都应该开始使用UTF-8?