如何解决FileReader“吃”每个第一个字母
我有一个代码:
File readFile = new File("acc\\10001.txt");
protected void readData(File file){
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while(reader.read() != -1){
System.out.println(reader.readLine());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null,ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,ex);
}
}
方法位于Main类的构造函数中。启动项目时,控制台会显示(例如):“ est”代替“ Test”,“ 0001”代替“ 10001”。
它适用于所有字符串和整数。
我们非常感谢您的帮助。
解决方法
您的代码段:
while(reader.read() != -1){
System.out.println(reader.readLine());
}
每次评估while条件时都会读取一个字符(read()
被调用并且it reads next character。
使用更好的方法更改代码:
String line="";
while ((line=reader.readLine()) != null) { //variable line gets assigned with value and then it's checked against null
System.out.println(line);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。