首页 > 技术文章 > InputStreamReader读文件自定义格式或消除乱码

nbfangzhu 2021-11-10 11:53 原文

1. 写一段代码,要求能够读出.txt文件中的内容,如果有中文,、保证不会乱码
String fr ="C:\\Users\\Administrator\\Desktop\\test.txt";
InputStreamReader isr = null;

try {
// fr =new FileReader("C:\\Users\\Administrator\\Desktop\\test.txt");
isr =new InputStreamReader(new FileInputStream(fr),"utf-8");
char [] fil = new char [1024];
while (isr.read(fil)!=-1) {
System.out.println(fil);
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
try {
isr.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}

推荐阅读