InputStream读取文件乱码

测试InputStream,读取一个中文文本,但发现在控制台上输出时,是乱码:

public class InputStream {
public static void main(String[] args) {
FileInputStream in = null;
int b;
long num = 0;
try {
//建立了一根管道,读取一个文件
in = new FileInputStream("L:\\Program Files\\test.txt");
while((b=in.read())!= -1) {
System.out.print((char)b);
num ++;
}
} catch (FileNotFoundException e) {
System.out.println("找不到指定文件!");
System.exit(-1);
} catch (IOException e) {
System.out.println("文件读取错误");
System.exit(-1);
}
}
}

因为:

b=in.read())是读取一个字节,然后(char)b肯定会是乱码。
in = new FileInputStream("L:\\Program Files\\test.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line=null;
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/DryKillLogic/archive/2009/12/11/4984402.aspx

原帖:http://blog.csdn.net/DryKillLogic/archive/2009/12/11/4984402.aspx

posted on 2011-04-17 23:27  Eason Jiang  阅读(3281)  评论(0编辑  收藏  举报

导航