1.正常的写代码是:(但是这样读取中文会出现乱码的情况)
FileInputStream fis=null;
try {
fis= new FileInputStream("src/temp");
byte[]bytes=new byte[4];
int readData;
while((readData=fis.read(bytes))!=-1){
System.out.print(new String(bytes,0,readData));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.解决方法:
FileInputStream fis=null;
try {
fis= new FileInputStream("src/temp");
Reader reader=new InputStreamReader(fis,"utf-8");
char[] chars=new char[4];
int readData;
while((readData=reader.read(chars))!=-1){
System.out.print(new String(chars,0,readData));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明:本文为w1256466374原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。