在读取文件时,通过这种批量读取时,发生了多读取了字符;
源文件:
而实际操作读取如下:
public static void main(String[] args) {
//文件路径
File file =new File("phone.xml");
//系统平台的编码是utf-8
// System.out.println(System.getProperty("file.encoding"));
//
System.out.println("文件大小:"+file.length());
int len=0;
//中转站
char[] ch=new char[100];
//文件读取对象
try (FileReader reader = new FileReader(file) ){
//读取一个
// len= reader.read();
// System.out.println((char)len);
//批量读取
// len =reader.read(ch);
// System.out.println(ch);
int count=0;
//循环输出
while((len =reader.read(ch))!=-1 ) {
System.out.println("第"+count+"次"+len);
System.out.println(ch);
// 必须用字符串方法指定实际大小
//System.out.println(new String(ch, 0, len));
count++; //累计
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
效果:
原因:
//中转站
char[] ch=new char[100];
while((len =reader.read(ch))!=-1 ) {
System.out.println(ch); //这个是问题的关键,虽然是45个字符,但ch是要输出100个字符,那么就会向上读取满100个;
}
解决:必须指定实际的大小!!!
while((len =reader.read(ch))!=-1 ) {
// 必须用字符串方法指定实际大小
System.out.println(new String(ch, 0, len));
}
效果: